﻿using DGZImp.Core.EFDbContext;
using DGZImp.Core.Exceptions;
using DGZImp.Core.Extensions;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using DGZImp.Core.DbSqlSugar;
using System.Security.Cryptography;
using DocumentFormat.OpenXml.Office2019.Excel.RichData2;
using ATkg.BizAppProject.DomainModels;
using DocumentFormat.OpenXml.Office2010.Excel;

using MailKit.Net.Smtp;
using MimeKit;
using System.Text.RegularExpressions;
using System.DirectoryServices.ActiveDirectory;
using DocumentFormat.OpenXml.Vml;
using DocumentFormat.OpenXml.Presentation;
using MySqlX.XDevAPI.Common;
using static ATkg.BizAppProject.Controllers.AmesSyncBizController;
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml.EMMA;
using System.Text.Json;
using DocumentFormat.OpenXml.Spreadsheet;
using System.Text.Json.Nodes;
using System;




namespace ATkg.BizAppProject.Services
{
    public class AmesSyncService : IDependency
    {
        public ISqlSugarClient Db = AutofacContainerModule.GetService<ServiceDbContext>()?.SqlSugarClient;
        public IConfiguration _config;
        public HttpClient client = null;
        public static IHttpClientFactory _httpClientFactory { get; set; }

        public string url = "";
        public string db = "";
        public string userName = "";
        public string password = "";

        public string url_kg_device = "";
        public string db_kg_device = "";
        public string userName_kg_device = "";
        public string password_kg_device = "";

        public string url_aike = "";
        public string db_aike = "";
        public string userName_aike = "";
        public string password_aike = "";

        public string url_beifang = "";
        public string db_beifang = "";
        public string userName_beifang = "";
        public string password_beifang = "";

        public static int? uid = 0;

        public ILogger<AmesSyncService> logger { get; set; }

        public AmesSyncService(IConfiguration configuration, IHttpClientFactory httpClientFactory)
        {
            _config = configuration;
            _httpClientFactory = httpClientFactory;
            this.url = _config["Interfaces:AnTaiMes:Url"];
            this.db = _config["Interfaces:AnTaiMes:Db"];
            this.userName = _config["Interfaces:AnTaiMes:UserName"];
            this.password = _config["Interfaces:AnTaiMes:Password"];

            this.url_kg_device = _config["Interfaces:AnTaiMesKgDevice:Url"];
            this.db_kg_device = _config["Interfaces:AnTaiMesKgDevice:Db"];
            this.userName_kg_device = _config["Interfaces:AnTaiMesKgDevice:UserName"];
            this.password_kg_device = _config["Interfaces:AnTaiMesKgDevice:Password"];

            this.url_aike = _config["Interfaces:AiKeMes:Url_AiKe"];
            this.db_aike = _config["Interfaces:AiKeMes:Db_AiKe"];
            this.userName_aike = _config["Interfaces:AiKeMes:UserName_AiKe"];
            this.password_aike = _config["Interfaces:AiKeMes:Password_AiKe"];

            this.url_beifang = _config["Interfaces:BfMes:Url_Bf"];
            this.db_beifang = _config["Interfaces:BfMes:Db_Bf"];
            this.userName_beifang = _config["Interfaces:BfMes:UserName_Bf"];
            this.password_beifang = _config["Interfaces:BfMes:Password_Bf"];
        }

        /// <summary>
        /// 调用AMES接口 通用方法
        /// </summary>
        public async Task<JObject> Call(string service, string method, List<dynamic> args)
        {
            client = _httpClientFactory.CreateClient();
            var json = new
            {
                jsonrpc = "2.0",
                method = "call",
                @params = new { service = service, method = method, args = args },
                id = Guid.NewGuid(),
            };
            try
            {
                Console.WriteLine(JsonConvert.SerializeObject(json));
                //Console.WriteLine("准备获取uid1");
                var content = new StringContent(JsonConvert.SerializeObject(json), Encoding.UTF8, "application/json");
                //Console.WriteLine("准备获取uid2");
                Console.WriteLine(content);
                //logger.LogInformation("---开始请求AMES获取数据---");
                //logger.LogInformation(JsonConvert.SerializeObject(json));
                client.Timeout = TimeSpan.FromSeconds(300);
                //Console.WriteLine("准备获取uid3");
                Console.WriteLine(url, content);
                var response = await client.PostAsync(url, content);
                //Console.WriteLine("准备获取uid4");
                response.EnsureSuccessStatusCode();
                //Console.WriteLine("准备获取uid5");
                var responseString = await response.Content.ReadAsStringAsync();
                //Console.WriteLine("准备获取uid6");
                //logger.LogInformation(responseString);
                var responseJson = JObject.Parse(responseString);
                //Console.WriteLine("准备获取uid7");
                return responseJson;
            }
            catch (Exception e)
            {
                throw new AppException(e.Message);
            }
        }

        public async Task<JObject> Call_Kg_Device(string service, string method, List<dynamic> args)
        {
            client = _httpClientFactory.CreateClient();
            var json = new
            {
                jsonrpc = "2.0",
                method = "call",
                @params = new { service = service, method = method, args = args },
                id = Guid.NewGuid(),
            };
            try
            {
                Console.WriteLine(JsonConvert.SerializeObject(json));
                //Console.WriteLine("准备获取uid1");
                var content = new StringContent(JsonConvert.SerializeObject(json), Encoding.UTF8, "application/json");
                //Console.WriteLine("准备获取uid2");
                Console.WriteLine(content);
                //logger.LogInformation("---开始请求AMES获取数据---");
                //logger.LogInformation(JsonConvert.SerializeObject(json));
                client.Timeout = TimeSpan.FromSeconds(300);
                //Console.WriteLine("准备获取uid3");
                Console.WriteLine(url, content);
                var response = await client.PostAsync(url_kg_device, content);
                //Console.WriteLine("准备获取uid4");
                response.EnsureSuccessStatusCode();
                //Console.WriteLine("准备获取uid5");
                var responseString = await response.Content.ReadAsStringAsync();
                //Console.WriteLine("准备获取uid6");
                //logger.LogInformation(responseString);
                var responseJson = JObject.Parse(responseString);
                //Console.WriteLine("准备获取uid7");
                return responseJson;
            }
            catch (Exception e)
            {
                throw new AppException(e.Message);
            }
        }

        public async Task<JObject> Call_AiKe(string service, string method, List<dynamic> args)
        {
            client = _httpClientFactory.CreateClient();
            var json = new
            {
                jsonrpc = "2.0",
                method = "call",
                @params = new { service = service, method = method, args = args },
                id = Guid.NewGuid(),
            };
            try
            {
                Console.WriteLine(JsonConvert.SerializeObject(json));
                var content = new StringContent(JsonConvert.SerializeObject(json), Encoding.UTF8, "application/json");
                //logger.LogInformation("---开始请求AMES获取数据---");
                //logger.LogInformation(JsonConvert.SerializeObject(json));
                client.Timeout = TimeSpan.FromSeconds(300);
                var response = await client.PostAsync(url_aike, content);
                response.EnsureSuccessStatusCode();
                var responseString = await response.Content.ReadAsStringAsync();
                //logger.LogInformation(responseString);
                var responseJson = JObject.Parse(responseString);
                return responseJson;
            }
            catch (Exception e)
            {
                throw new AppException(e.Message);
            }
        }

        public async Task<JObject> Call_BeiFang(string service, string method, List<dynamic> args)
        {
            client = _httpClientFactory.CreateClient();
            var json = new
            {
                jsonrpc = "2.0",
                method = "call",
                @params = new { service = service, method = method, args = args },
                id = Guid.NewGuid(),
            };
            try
            {
                Console.WriteLine(JsonConvert.SerializeObject(json));
                var content = new StringContent(JsonConvert.SerializeObject(json), Encoding.UTF8, "application/json");
                //logger.LogInformation("---开始请求AMES获取数据---");
                //logger.LogInformation(JsonConvert.SerializeObject(json));
                client.Timeout = TimeSpan.FromSeconds(300);
                var response = await client.PostAsync(url_beifang, content);
                response.EnsureSuccessStatusCode();
                var responseString = await response.Content.ReadAsStringAsync();
                //logger.LogInformation(responseString);
                var responseJson = JObject.Parse(responseString);
                return responseJson;
            }
            catch (Exception e)
            {
                throw new AppException(e.Message);
            }
        }

        public async Task<JObject> CallRead_purchase_KongGang(string model, int id)
        {
            Console.WriteLine("wwwwww");
            var param = new List<object>();
            param.Add(db);
            //if (uid == null || uid == 0)
            uid = await GetOdooUid(userName, password);
            param.Add(uid);
            param.Add(password);
            param.Add(model);
            param.Add("read");
            //param.Add(new List<object> { id });
            var qDomain = new List<object> {
                id
            };
            var qFields = new List<string> {
                "name",
                "spec",
                "product_qty",
                "price_unit",
                "base_price",
                "price_subtotal",
                "total",
                "product_uom"
            };
            param.Add(new List<object> { qDomain, qFields });
            JObject data = null;
            try
            {
                data = await Call("object", "execute_kw", param);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"获取aMES数据失败，请求内容：{JsonConvert.SerializeObject(param)}，错误信息：{ex.Message}");
                throw new AppException(ex.ToString());
            }
            Console.WriteLine(data);
            return data;
        }
        public async Task<JObject> CallRead_purchase_AiKe(string model, int id)
        {
            Console.WriteLine("wwwwww");
            var param = new List<object>();
            param.Add(db_aike);
            //if (uid == null || uid == 0)
            uid = await GetOdooUid_AiKe(userName_aike, password_aike);
            param.Add(uid);
            param.Add(password_aike);
            param.Add(model);
            param.Add("read");
            //param.Add(new List<object> { id });
            var qDomain = new List<object> {
                //new List<object> { "id", "=", id }
                id
            };
            var qFields = new List<string> {
                "name",
                "spec",
                "product_qty",
                "price_unit",
                "base_price",
                "price_subtotal",
                "total",
                "product_uom"
            };
            param.Add(new List<object> { qDomain, qFields });
            JObject data = null;
            try
            {
                data = await Call_AiKe("object", "execute_kw", param);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"获取aMES数据失败，请求内容：{JsonConvert.SerializeObject(param)}，错误信息：{ex.Message}");
                throw new AppException(ex.ToString());
            }
            Console.WriteLine(data);
            return data;
        }
        public async Task<JObject> CallRead_purchase_BeiFang(string model, int id)
        {
            Console.WriteLine("wwwwww");
            var param = new List<object>();
            param.Add(db_beifang);
            //if (uid == null || uid == 0)
                uid = await GetOdooUid_BeiFang(userName_beifang, password_beifang);
            param.Add(uid);
            param.Add(password_beifang);
            param.Add(model);
            param.Add("web_read");
            param.Add(new List<object> { id });
            var orderIdFields = new Dictionary<string, object>
            {
                { "fields", new Dictionary<string, object>() }
            };

            var productUomFields = new Dictionary<string, object>
            {
                //{ "id", new Dictionary<string, object>() },
                { "fields", new Dictionary<string, object>
                    { 
                        { 
                            "display_name", new Dictionary<string, object>() 
                        }  
                    } 
                }
                     
                
            };

            // 创建order_line的fields结构
            var orderLineFields = new Dictionary<string, object>
            {
                {"order_id", orderIdFields },
                {"name", new Dictionary<string, object>() },
                {"spec", new Dictionary<string, object>() },
                {"product_qty", new Dictionary<string, object>() },
                {"price_unit", new Dictionary<string, object>() },
                {"product_uom", productUomFields },
                {"base_price", new Dictionary<string, object>() },
                {"price_subtotal", new Dictionary<string, object>() },
                {"total", new Dictionary<string, object>() },
            };

            // 创建order_line结构
            var orderLine = new Dictionary<string, object>
            {
                { "fields", orderLineFields }
            };

            // 创建specification结构
            var specification = new Dictionary<string, object>
            {
                { "all_arrival_notice_done", new Dictionary<string, object>() },
                { "order_line", orderLine }
            };

            // 创建最终结果
            var result = new Dictionary<string, object>
            {
                { "specification", specification }
            };
            param.Add(result);
            JObject data = null;
            try
            {
                data = await Call_BeiFang("object", "execute_kw", param);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"获取aMES数据失败，请求内容：{JsonConvert.SerializeObject(param)}，错误信息：{ex.Message}");
                throw new AppException(ex.ToString());
            }
            Console.WriteLine(data);
            return data;
        }

        public async Task<object> CallRead_Product_BeiFang(string name)
        {
            //先通过另一个接口获取该产品代码ID
            var id = (JObject)await SyncProduction_BF(name);
            if (id == null)
            {
                return null;      
            }
            Console.WriteLine("wwwwww");
            var param = new List<object>();
            param.Add(db_beifang);
            //if (uid == null || uid == 0)
            uid = await GetOdooUid_BeiFang(userName_beifang, password_beifang);
            param.Add(uid);
            param.Add(password_beifang);
            param.Add("atm.plm.top");
            param.Add("web_read"); //进入详细行读取详细信息
            param.Add(new List<object> { (int)id["id"] });
            var orderIdFields = new Dictionary<string, object>
            {
                { "fields", new Dictionary<string, object>() }
            };

            var productUomFields = new Dictionary<string, object>
            {
                //{ "id", new Dictionary<string, object>() },
                { "fields", new Dictionary<string, object>
                    {
                        { "display_name", new Dictionary<string, object>() }
                    }
                }


            };

            // 创建order_line的fields结构
            var orderLineFields = new Dictionary<string, object>
            {
                {"order_id", orderIdFields },
                {"name", new Dictionary<string, object>() },
                {"product_qty", new Dictionary<string, object>() },
                {"price_unit", new Dictionary<string, object>() },
                {"product_uom", productUomFields },
                {"base_price", new Dictionary<string, object>() },
                {"price_subtotal", new Dictionary<string, object>() },
                {"total", new Dictionary<string, object>() },
            };

            // 创建order_line结构
            var orderLine = new Dictionary<string, object>
            {
                { "fields", orderLineFields }
            };

            var displayFields = new Dictionary<string, object>
            {
                { "fields", new Dictionary<string, object>
                    {
                        { "display_name", new Dictionary<string, object>() }
                    }
                }
            };
            var machining_sheet_idsFields = new Dictionary<string, object>
            {
                { "fields", new Dictionary<string, object>
                    {
                        { "id", new Dictionary<string, object>() },
                        { "mrp_workcenter_id", displayFields }
                    }
                }
            };
            var test_idsFields = new Dictionary<string, object>
            {
                { "fields", new Dictionary<string, object>
                    {
                        { "id", new Dictionary<string, object>() },
                        { "inspect_type_id", displayFields }
                    }
                }
            };

            // 创建specification结构
            var specification = new Dictionary<string, object>
            {
                { "grade", displayFields },
                { "plating", displayFields },
                { "partner_blueprint_no", new Dictionary<string, object>() },
                { "partner_blueprint_version", new Dictionary<string, object>() },
                { "atmcn_blueprint_no", new Dictionary<string, object>() },
                { "part_name", new Dictionary<string, object>() },
                { "part_no", new Dictionary<string, object>() },
                { "product_remark", new Dictionary<string, object>() },
                { "experimental", new Dictionary<string, object>() },
                { "application", displayFields },
                { "magnetizing", new Dictionary<string, object>() },
                { "byproduct_top_ids", displayFields },
                { "share_top_ids", displayFields },
                { "plant_ids", displayFields },
                { "rough_shape", displayFields },
                { "product_shape", displayFields },
                { "machining_sheet_ids", machining_sheet_idsFields },
                { "permeation_sheet_ids", machining_sheet_idsFields },
                { "plating_sheet_ids", machining_sheet_idsFields },
                { "blank_test_ids", test_idsFields },
                { "white_test_ids", test_idsFields },
            };

            // 创建最终结果
            var result = new Dictionary<string, object>
            {
                { "specification", specification }
            };
            param.Add(result);
            JObject data = null;
            try
            {
                data = await Call_BeiFang("object", "execute_kw", param);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"获取aMES数据失败，请求内容：{JsonConvert.SerializeObject(param)}，错误信息：{ex.Message}");
                throw new AppException(ex.ToString());
            }
            var magnetMapping = new Dictionary<string, string>
            {
                ["none"] = "不充磁",
                ["half"] = "半充磁",
                ["full"] = "充磁"
            };
            List<int> machiningSheetIdsList = new List<int>();
            List<int> permeationSheetIdsList = new List<int>();
            List<int> platingSheetIdsList = new List<int>();
            List<List<object>> blankTestIdsNames = new List<List<object>>();
            List<List<object>> whiteTestIdsNames = new List<List<object>>();
            List<List<object>> platingSheetIdsNames = new List<List<object>>();
            foreach (var item in data["result"][0]["machining_sheet_ids"])
            {
                machiningSheetIdsList.Add((int)item["id"]);
            }
            foreach (var item in data["result"][0]["permeation_sheet_ids"])
            {
                permeationSheetIdsList.Add((int)item["id"]);
            }
            foreach (var item in data["result"][0]["plating_sheet_ids"])
            {
                platingSheetIdsList.Add((int)item["id"]);
                platingSheetIdsNames.Add(new List<object> { (int)item["id"], (string)item["mrp_workcenter_id"]["display_name"] });
            }
            foreach (var item in data["result"][0]["blank_test_ids"])
            {
                blankTestIdsNames.Add(new List<object> { (int)item["id"], (string)item["inspect_type_id"]["display_name"] });
            }
            foreach (var item in data["result"][0]["white_test_ids"])
            {
                whiteTestIdsNames.Add(new List<object> { (int)item["id"], (string)item["inspect_type_id"]["display_name"] });
            }
            var r = new List<object>();
            r.Add( new
            {
                //字典类型：先判断是否是bool类型，再判断是否是false
                Grade = (data["result"][0]["grade"]?.Type == JTokenType.Boolean && data["result"][0]["grade"].Value<bool>() == false) ? "" : data["result"][0]["grade"]["display_name"].ToString(),
                Plating = (data["result"][0]["plating"]?.Type == JTokenType.Boolean && data["result"][0]["plating"].Value<bool>() == false) ? "" : data["result"][0]["plating"]["display_name"].ToString(),
                Application = (data["result"][0]["application"]?.Type == JTokenType.Boolean && data["result"][0]["application"].Value<bool>() == false) ? "" : data["result"][0]["application"]["display_name"].ToString(),

                //单字段类型：先判断是否是bool类型，再判断是否是false
                PartnerBlueprintNo = (data["result"][0]["partner_blueprint_no"]?.Type == JTokenType.Boolean && data["result"][0]["partner_blueprint_no"].Value<bool>() == false) ? "" : data["result"][0]["partner_blueprint_no"].ToString(),
                PartnerBlueprintVersion = (data["result"][0]["partner_blueprint_version"]?.Type == JTokenType.Boolean && data["result"][0]["partner_blueprint_version"].Value<bool>() == false) ? "" : data["result"][0]["partner_blueprint_version"].ToString(),
                AtmcnBlueprintNo = (data["result"][0]["atmcn_blueprint_no"]?.Type == JTokenType.Boolean && data["result"][0]["atmcn_blueprint_no"].Value<bool>() == false) ? "" : data["result"][0]["atmcn_blueprint_no"].ToString(),
                PartName = (data["result"][0]["part_name"]?.Type == JTokenType.Boolean && data["result"][0]["part_name"].Value<bool>() == false) ? "" : data["result"][0]["part_name"].ToString(),
                PartNo = (data["result"][0]["part_no"]?.Type == JTokenType.Boolean && data["result"][0]["part_no"].Value<bool>() == false) ? "" : data["result"][0]["part_no"].ToString(),
                ProductRemark = (data["result"][0]["product_remark"]?.Type == JTokenType.Boolean && data["result"][0]["product_remark"].Value<bool>() == false) ? "" : data["result"][0]["product_remark"].ToString(),
                //勾选类型
                //Exterimental = (bool)data["result"][0]["experimental"] ? "是" : "否",
                Exterimental = (bool)data["result"][0]["experimental"],
                //单选（字段）类型
                Magnetizing = (data["result"][0]["magnetizing"]?.Type == JTokenType.Boolean && data["result"][0]["magnetizing"].Value<bool>() == false) ? "": magnetMapping.TryGetValue(data["result"][0]["magnetizing"]?.ToString() ?? "", out var value)? value: "未知充磁类型",
                //多选（字典）类型
                //ShareTopIds = data["result"][0]["share_top_ids"][0]["display_name"].ToString(),
                //PlantIds = data["result"][0]["plant_ids"][0]["display_name"].ToString(),
                //ByproductTopIds = data["result"][0]["byproduct_top_ids"][0]["display_name"].ToString(),
                RoughShape = (data["result"][0]["rough_shape"]?.Type == JTokenType.Boolean && data["result"][0]["rough_shape"].Value<bool>() == false) ? "" : data["result"][0]["rough_shape"]["display_name"].ToString(),
                ProductShape = (data["result"][0]["product_shape"]?.Type == JTokenType.Boolean && data["result"][0]["product_shape"].Value<bool>() == false) ? "" : data["result"][0]["product_shape"]["display_name"].ToString(),
                RoughShapeId = (data["result"][0]["rough_shape"]?.Type == JTokenType.Boolean && data["result"][0]["rough_shape"].Value<bool>() == false) ? "" : data["result"][0]["rough_shape"]["id"],
                ProductShapeId = (data["result"][0]["product_shape"]?.Type == JTokenType.Boolean && data["result"][0]["product_shape"].Value<bool>() == false) ? "" : data["result"][0]["product_shape"]["id"],

                MachiningSheetIds = machiningSheetIdsList,
                PermeationSheetIds = permeationSheetIdsList,
                PlatingSheetIds = platingSheetIdsList,
                PlatingSheetIdsNames = platingSheetIdsNames,
                BlankTestIdsNames = blankTestIdsNames,
                WhiteTestIdsNames = whiteTestIdsNames,
            });
            Console.WriteLine(data);
            //return r;
            return new
            {
                rows = r,
                total = r.Count
            };
        }

        public static int[][] ConvertListToJaggedArray(List<int> inputList)
        {
            if (inputList == null)
                throw new ArgumentNullException(nameof(inputList));

            int[][] jaggedArray = new int[inputList.Count][];

            for (int i = 0; i < inputList.Count; i++)
            {
                jaggedArray[i] = new int[2];       // 每行固定 2 列
                jaggedArray[i][0] = 4;             // 第一列固定 4
                jaggedArray[i][1] = inputList[i];   // 第二列取 list 的值
            }

            return jaggedArray;
        }
        // 单独的方法用于生成geo_tol_lines列表
        private List<object> CreateGeoTolLines(dynamic readOrWrite)
        {
            var lines = new List<object>();

            // 添加GeoType1条目（如果存在）
            if (!string.IsNullOrEmpty(readOrWrite["GeoType1"]?.ToString()))
            {
                lines.Add(CreateGeoTolItem(0, "virtual_27",
                    readOrWrite["GeoType1"],
                    readOrWrite["GeoRemark1"],
                    readOrWrite["GeoValue1"]));
            }

            // 添加GeoType2条目（如果存在）
            if (!string.IsNullOrEmpty(readOrWrite["GeoType2"]?.ToString()))
            {
                lines.Add(CreateGeoTolItem(0, "virtual_28",
                    readOrWrite["GeoType2"],
                    readOrWrite["GeoRemark2"],
                    readOrWrite["GeoValue2"]));
            }

            // 添加GeoType3条目（如果存在）
            if (!string.IsNullOrEmpty(readOrWrite["GeoType3"]?.ToString()))
            {
                lines.Add(CreateGeoTolItem(0, "virtual_29",
                    readOrWrite["GeoType3"],
                    readOrWrite["GeoRemark3"],
                    readOrWrite["GeoValue3"]));
            }

            // 添加GeoType4条目（如果存在）
            if (!string.IsNullOrEmpty(readOrWrite["GeoType4"]?.ToString()))
            {
                lines.Add(CreateGeoTolItem(0, "virtual_30",
                    readOrWrite["GeoType4"],
                    readOrWrite["GeoRemark4"],
                    readOrWrite["GeoValue4"]));
            }

            // 添加GeoType5条目（如果存在）
            if (!string.IsNullOrEmpty(readOrWrite["GeoType5"]?.ToString()))
            {
                lines.Add(CreateGeoTolItem(0, "virtual_31",
                    readOrWrite["GeoType5"],
                    readOrWrite["GeoRemark5"],
                    readOrWrite["GeoValue5"]));
            }

            return lines;
        }

        // 辅助方法：创建单个形位公差条目
        private object CreateGeoTolItem(int number, string virtualKey,
                                      dynamic geoType, dynamic remark, dynamic value)
        {
            return new List<object>
                    {
                        number,
                        virtualKey,
                        new Dictionary<string, object>
                        {
                            {"geo_type", geoType},
                            {"remark", remark},
                            {"value", value}
                        }
                    };
        }
        public async Task<object> CallWrite_Product_BeiFang(string name, Dictionary<object, object> readOrWrite)
        {
            //上传git前要把这个剪切掉，不能直接把明文写到代码中
            if ((string)readOrWrite["UserName"] == "牛希媛")
            {
                this.userName_beifang = "niuxiyuan@atmcn.com";
                this.password_beifang = "Antai@2025";
            }
            else if ((string)readOrWrite["UserName"] == "郝玉敬")
            {
                this.userName_beifang = "haoyujing@atmcn.com";
                this.password_beifang = "Antai@2025";
            }
            else if ((string)readOrWrite["UserName"] == "王升")
            {
                this.userName_beifang = "wangsheng@atmcn.com";
                this.password_beifang = "Antai@2025";
            }
            else if ((string)readOrWrite["UserName"] == "蔡君兰")
            {
                this.userName_beifang = "caijunlan@atmcn.com";
                this.password_beifang = "Antai@2025";
            }
            else if ((string)readOrWrite["UserName"] == "陈明")
            {
                this.userName_beifang = "chenming@atmcn.com";
                this.password_beifang = "Antai@2025";
            }

            //先通过另一个接口获取该产品代码ID
            if (name?.Length < 7 | name == null)
            {
                return new
                {
                    rows = new List<string>(),
                    total = 0
                };
            }
            var id = (JObject)await SyncProduction_BF(name);
            if (id == null)
            {
                return null;
            }

            Console.WriteLine("wwwwww");
            var param = new List<object>();
            param.Add(db_beifang);
            if (uid == null || uid == 0)
                uid = await GetOdooUid_BeiFang(userName_beifang, password_beifang);
            param.Add(uid);
            param.Add(password_beifang);
            param.Add("atm.plm.top");//修改产品工艺单中的内容模型
            //param.Add("write");
            //(    db, uid, password, 'atm.plm.top', 'web_save',
            //[ [id],{"product_remark":"234"} ], { "specification":{ } }    )   python版本
            //param.Add("web_save");
            param.Add("write");  //web_save  write都可以修改参数，write不需要传入specification参数
            int[,] array2D = new int[2, 2] { { 4, 1 }, { 4, 2 } };  //添加是41  42 添加宁波和D座 删除是31  32 4是新增的意思，3是删除的意思
            int[,] array1D1 = new int[1, 2] { { 4, 1 } };  //添加宁波工厂
            int[,] array1D2 = new int[1, 2] { { 4, 2 } };  //添加是D座
            List<int> byproductTopIds = ((JArray)readOrWrite["ByproductTopIds"]).Select(x => (int)x).ToList();
            List<int> shareTopIds = ((JArray)readOrWrite["ShareTopIds"]).Select(x => (int)x).ToList();
            List<string> plantIds = ((JArray)readOrWrite["PlantIds"]).Select(x => (string)x).ToList();
            int[][] byproductTopIdsArray = ConvertListToJaggedArray(byproductTopIds);
            int[][] shareTopIdsArray = ConvertListToJaggedArray(shareTopIds);
            var applicationMap = new Dictionary<string, int>
            {
                ["工业电机"] = 6,
                ["喇叭音响"] = 7,
                ["汽车车载"] = 13,
                ["消费品电子"] = 9,
                ["其他"] = 10,
                ["直线电机"] = 11,
                ["电动自行车"] = 12,
                ["车载汽车"] = 8,
            };
            string Application = (string)readOrWrite["Application"];
            int ApplicationCode = applicationMap.TryGetValue(Application.Trim(), out int code) ? code : 0;

            //修改成品
            if (name.Contains("Z"))
            {  //修改成品
                var vals = new Dictionary<string, object>
                {
                        //{ "name", readOrWrite.Name },  // 还不能轻易修改产品代码
                        { "atmcn_blueprint_no", readOrWrite["AtmcnBlueprintNo"] },  // 修改安泰图纸号（已成功）
                        //{ "grade", 64 },  // 修改性能，目前只能通过变更修改
                        { "part_name", readOrWrite["PartName"] },  // 修改零件名称/SAP（已成功）
                        { "part_no", readOrWrite["PartNo"] },  // 修改零件号/组装号（已成功）
                        { "product_remark", readOrWrite["ProductRemark"] },  // 修改产品备注（已成功）
                        { "experimental", readOrWrite["Exterimental"].ToString() == "1" ? true : false },  // 修改实验产品（已成功）磁云平台中传回的是"1"，
                        { "blank_for_sale_ok", readOrWrite["BlankForSaleOk"].ToString() == "1" ? true : false },  // 修改毛坯发货
                        { "application", ApplicationCode},  // 修改应用类型（已成功）应用类型上传的是ID
                        { "byproduct_top_ids", byproductTopIdsArray },  // 修改产出其他产品（已成功）
                        { "share_top_ids", shareTopIdsArray },  // 修改共享库存工艺单（已成功）
                        { "plant_ids", plantIds.Count == 2 ? array2D :plantIds[0].ToString() == "宁波工厂" ? array1D1 : array1D2},  // 修改所属工厂（已成功）
                        { "oem_product_ok", readOrWrite["OemProductOk"].ToString() == "1" ? true : false },  // 修改OEM产品 
                        { "recycle_flag", readOrWrite["RecycleFlg"].ToString() == "1" ? true : false },  // 修改再循环材料制作
                        { "original_product_code", readOrWrite["OriginalProductCode"] },  // 修改原发产品代码
                        { "remark_cipianjiao", readOrWrite["RemarkCipianjiao"] },  // 修改磁偏角要求
                        { "weight_g", readOrWrite["Weight"] },  // 修改单重（已成功）
                        { "surface_area", readOrWrite["SurfaceArea"] },  // 修改表面积（已成功）
                        { "remark_cailiao", readOrWrite["RemarkCailiao"] },  // 修改材料其他要求（已成功）
                        { "remark_packaging", readOrWrite["RemarkPackaging"] },  // 修改出货要求（已成功）
                        { "material_grade", readOrWrite["MaterialGrade"] },  // 修改材料性能（已成功）
                        { "steelgrade_id", readOrWrite["SteelGradeId"] },  // 修改钢号
                        { "sintering_type", readOrWrite["SinteringType"] },  // 修改烧结工艺

                        { "grade_after_permeation", readOrWrite["GradeAfterPermeation"] },  // 修改渗透后磁性能（已成功）
                        { "daojiao_id", readOrWrite["DaojiaoId"] },  // 修改渗透后磁性能（已成功）
                        { "ducenghoudu_id", readOrWrite["DucenghouduId"] },  // 修改渗透后磁性能（已成功）
                        { "remark_diandu", readOrWrite["RemarkDiandu"] },  // 修改渗透后磁性能（已成功）
                        { "qty_per_chest", readOrWrite["QtyPerChest"] },  // 修改每箱数量（已成功）
                        { "qty_per_box", readOrWrite["QtyPerBox"] },  // 修改每盒数量（已成功）
                        { "qty_per_bag", readOrWrite["QtyPerBag"] },  // 修改每袋数量（已成功）
                        { "permeation_gongyi_id", readOrWrite["PermeationGongyiId"] },  // 修改渗透工艺
                        { "machining_sheet_ids", new List<object>  //修改加工工序-车间类型、工作中心（目前只添加1个）
                                                    {
                                                        new List<object>
                                                        {
                                                            0,
                                                            "virtual_23",//可以重复，但不能没有？
                                                            new Dictionary<string, object>  //添加1个工作中心
                                                            {
                                                                //{"sequence", 4},  //行号，没什么用，加了也是新增在最后一行
                                                                {"workcenter_type_id", readOrWrite["WorkcenterType1"]}, //车间类型
                                                                {"mrp_workcenter_id", readOrWrite["MrpWorkcenter1"]}, //工作中心
                                                            }
                                                        }

                                                    }

                        },
                        { "permeation_sheet_ids", new List<object>  //修改渗透工序-车间类型、工作中心（目前只添加1个）
                                                    {
                                                        new List<object>
                                                        {
                                                            0,
                                                            "virtual_24",//可以重复，但不能没有？
                                                            new Dictionary<string, object>  //添加1个工作中心
                                                            {
                                                                //{"sequence", 4},  //行号，没什么用，加了也是新增在最后一行
                                                                {"workcenter_type_id", readOrWrite["WorkcenterType2"]}, //车间类型
                                                                {"mrp_workcenter_id", readOrWrite["MrpWorkcenter2"]}, //工作中心
                                                            }
                                                        }

                                                    }

                        },
                        { "plating_sheet_ids", new List<object>  //修改电镀工序-车间类型、工作中心（目前添加2个）
                                                    {
                                                        new List<object>
                                                        {
                                                            0,
                                                            "virtual_25",//可以重复，但不能没有？
                                                            new Dictionary<string, object>  //添加1个工作中心
                                                            {
                                                                //{"sequence", 4},  //行号，没什么用，加了也是新增在最后一行
                                                                {"workcenter_type_id", readOrWrite["WorkcenterType3"]}, //车间类型
                                                                {"mrp_workcenter_id", readOrWrite["MrpWorkcenter3"]}, //工作中心
                                                            }

                                                        },
                                                        new List<object>
                                                        {
                                                            0,
                                                            "virtual_26",//可以重复，但不能没有？
                                                            new Dictionary<string, object>  //添加1个工作中心
                                                            {
                                                                //{"sequence", 4},  //行号，没什么用，加了也是新增在最后一行
                                                                {"workcenter_type_id", readOrWrite["WorkcenterType4"]}, //车间类型
                                                                {"mrp_workcenter_id", readOrWrite["MrpWorkcenter4"]}, //工作中心
                                                            }
                                                        }

                                                    }

                        },
                        { "blank_test_ids", new List<object>  //修改毛坯检测项目（目前添加1个
                                                    {
                                                        new List<object>
                                                        {
                                                            0,
                                                            "virtual_27",//可以重复，但不能没有？
                                                            new Dictionary<string, object>  //添加1个工作中心
                                                            {
                                                                //{"sequence", 4},  //行号，没什么用，加了也是新增在最后一行
                                                                {"inspect_type_id", readOrWrite["BlankInspectType1"]}, // 检测类型
                                                                {"oqc_ok", (readOrWrite["BlankInspectOQC1"].ToString()) == "1" ? true : false}, // OQC标记
                                                                {"qc_level", readOrWrite["BlankInspectQClevel1"]}, // QC等级
                                                                {"sample_qty", readOrWrite["BlankInspectSampleQty1"]}, // 送检数量
                                                            }

                                                        }

                                                    }

                        },
                        { "white_test_ids", new List<object>  //修改白片检测项目
                                                    {
                                                        new List<object> //镀层厚度检测
                                                        {
                                                            0,
                                                            "virtual_27",//可以重复，但不能没有？
                                                            new Dictionary<string, object>
                                                            {
                                                                //{"sequence", 4},  //行号，没什么用，加了也是新增在最后一行
                                                                {"inspect_type_id", readOrWrite["WhiteInspectType1"]}, // 检测类型
                                                                {"oqc_ok", readOrWrite["WhiteInspectOQC1"].ToString() == "1" ? true : false}, // OQC标记
                                                                {"qc_level", readOrWrite["WhiteInspectQClevel1"]}, // QC等级
                                                                {"sample_qty", readOrWrite["WhiteInspectSampleQty1"]}, // 送检数量
                                                            }

                                                        },
                                                        new List<object> //磁通检测
                                                        {
                                                            0,
                                                            "virtual_27",//可以重复，但不能没有？
                                                            new Dictionary<string, object>
                                                            {
                                                                //{"sequence", 4},  //行号，没什么用，加了也是新增在最后一行
                                                                {"inspect_type_id", readOrWrite["WhiteInspectType2"]}, // 检测类型
                                                                {"oqc_ok", readOrWrite["WhiteInspectOQC2"].ToString() == "1" ? true : false}, // OQC标记
                                                                {"qc_level", readOrWrite["WhiteInspectQClevel2"]}, // QC等级
                                                                {"sample_qty", readOrWrite["WhiteInspectSampleQty2"]}, // 送检数量
                                                            }

                                                        },
                                                        new List<object> //盐雾检测
                                                        {
                                                            0,
                                                            "virtual_27",//可以重复，但不能没有？
                                                            new Dictionary<string, object>
                                                            {
                                                                //{"sequence", 4},  //行号，没什么用，加了也是新增在最后一行
                                                                {"inspect_type_id", readOrWrite["WhiteInspectType3"]}, // 检测类型
                                                                {"oqc_ok", readOrWrite["WhiteInspectOQC3"].ToString() == "1" ? true : false}, // OQC标记
                                                                {"qc_level", readOrWrite["WhiteInspectQClevel3"]}, // QC等级
                                                                {"sample_qty", readOrWrite["WhiteInspectSampleQty3"]}, // 送检数量
                                                            }

                                                        },
                                                        new List<object> //表面张力检测
                                                        {
                                                            0,
                                                            "virtual_27",//可以重复，但不能没有？
                                                            new Dictionary<string, object>
                                                            {
                                                                //{"sequence", 4},  //行号，没什么用，加了也是新增在最后一行
                                                                {"inspect_type_id", readOrWrite["WhiteInspectType4"]}, // 检测类型
                                                                {"oqc_ok", readOrWrite["WhiteInspectOQC4"].ToString() == "1" ? true : false}, // OQC标记
                                                                {"qc_level", readOrWrite["WhiteInspectQClevel4"]}, // QC等级
                                                                {"sample_qty", readOrWrite["WhiteInspectSampleQty4"]}, // 送检数量
                                                            }

                                                        },
                                                        new List<object> //胶带检测
                                                        {
                                                            0,
                                                            "virtual_27",//可以重复，但不能没有？
                                                            new Dictionary<string, object>
                                                            {
                                                                //{"sequence", 4},  //行号，没什么用，加了也是新增在最后一行
                                                                {"inspect_type_id", readOrWrite["WhiteInspectType5"]}, // 检测类型
                                                                {"oqc_ok", readOrWrite["WhiteInspectOQC5"].ToString() == "1" ? true : false}, // OQC标记
                                                                {"qc_level", readOrWrite["WhiteInspectQClevel5"]}, // QC等级
                                                                {"sample_qty", readOrWrite["WhiteInspectSampleQty5"]}, // 送检数量
                                                            }

                                                        },
                                                        new List<object> //湿热检测
                                                        {
                                                            0,
                                                            "virtual_27",//可以重复，但不能没有？
                                                            new Dictionary<string, object>
                                                            {
                                                                //{"sequence", 4},  //行号，没什么用，加了也是新增在最后一行
                                                                {"inspect_type_id", readOrWrite["WhiteInspectType6"]}, // 检测类型
                                                                {"oqc_ok", readOrWrite["WhiteInspectOQC6"].ToString() == "1" ? true : false}, // OQC标记
                                                                {"qc_level", readOrWrite["WhiteInspectQClevel6"]}, // QC等级
                                                                {"sample_qty", readOrWrite["WhiteInspectSampleQty6"]}, // 送检数量
                                                            }

                                                        },
                                                        new List<object> //PCT检测
                                                        {
                                                            0,
                                                            "virtual_27",//可以重复，但不能没有？
                                                            new Dictionary<string, object>
                                                            {
                                                                //{"sequence", 4},  //行号，没什么用，加了也是新增在最后一行
                                                                {"inspect_type_id", readOrWrite["WhiteInspectType7"]}, // 检测类型
                                                                {"oqc_ok", readOrWrite["WhiteInspectOQC7"].ToString() == "1" ? true : false}, // OQC标记
                                                                {"qc_level", readOrWrite["WhiteInspectQClevel7"]}, // QC等级
                                                                {"sample_qty", readOrWrite["WhiteInspectSampleQty7"]}, // 送检数量
                                                            }

                                                        },
                                                        new List<object> //PCT检测
                                                        {
                                                            0,
                                                            "virtual_27",//可以重复，但不能没有？
                                                            new Dictionary<string, object>
                                                            {
                                                                //{"sequence", 4},  //行号，没什么用，加了也是新增在最后一行
                                                                {"inspect_type_id", readOrWrite["WhiteInspectType8"]}, // 检测类型
                                                                {"oqc_ok", readOrWrite["WhiteInspectOQC8"].ToString() == "1" ? true : false}, // OQC标记
                                                                {"qc_level", readOrWrite["WhiteInspectQClevel8"]}, // QC等级
                                                                {"sample_qty", readOrWrite["WhiteInspectSampleQty8"]}, // 送检数量
                                                            }

                                                        },
                                                        new List<object> //PCT检测
                                                        {
                                                            0,
                                                            "virtual_27",//可以重复，但不能没有？
                                                            new Dictionary<string, object>
                                                            {
                                                                //{"sequence", 4},  //行号，没什么用，加了也是新增在最后一行
                                                                {"inspect_type_id", readOrWrite["WhiteInspectType9"]}, // 检测类型
                                                                {"oqc_ok", readOrWrite["WhiteInspectOQC9"].ToString() == "1" ? true : false}, // OQC标记
                                                                {"qc_level", readOrWrite["WhiteInspectQClevel9"]}, // QC等级
                                                                {"sample_qty", readOrWrite["WhiteInspectSampleQty9"]}, // 送检数量
                                                            }

                                                        },
                                                        new List<object> //失重
                                                        {
                                                            0,
                                                            "virtual_27",//可以重复，但不能没有？
                                                            new Dictionary<string, object>
                                                            {
                                                                //{"sequence", 4},  //行号，没什么用，加了也是新增在最后一行
                                                                {"inspect_type_id", readOrWrite["WhiteInspectType10"]}, // 检测类型
                                                                {"oqc_ok", readOrWrite["WhiteInspectOQC10"].ToString() == "1" ? true : false}, // OQC标记
                                                                {"qc_level", readOrWrite["WhiteInspectQClevel10"]}, // QC等级
                                                                {"sample_qty", readOrWrite["WhiteInspectSampleQty10"]}, // 送检数量
                                                            }

                                                        },
                                                        new List<object> //失重
                                                        {
                                                            0,
                                                            "virtual_27",//可以重复，但不能没有？
                                                            new Dictionary<string, object>
                                                            {
                                                                //{"sequence", 4},  //行号，没什么用，加了也是新增在最后一行
                                                                {"inspect_type_id", readOrWrite["WhiteInspectType11"]}, // 检测类型
                                                                {"oqc_ok", readOrWrite["WhiteInspectOQC11"].ToString() == "1" ? true : false}, // OQC标记
                                                                {"qc_level", readOrWrite["WhiteInspectQClevel11"]}, // QC等级
                                                                {"sample_qty", readOrWrite["WhiteInspectSampleQty11"]}, // 送检数量
                                                            }

                                                        },
                                                        new List<object> //失重
                                                        {
                                                            0,
                                                            "virtual_27",//可以重复，但不能没有？
                                                            new Dictionary<string, object>
                                                            {
                                                                //{"sequence", 4},  //行号，没什么用，加了也是新增在最后一行
                                                                {"inspect_type_id", readOrWrite["WhiteInspectType12"]}, // 检测类型
                                                                {"oqc_ok", readOrWrite["WhiteInspectOQC12"].ToString() == "1" ? true : false}, // OQC标记
                                                                {"qc_level", readOrWrite["WhiteInspectQClevel12"]}, // QC等级
                                                                {"sample_qty", readOrWrite["WhiteInspectSampleQty12"]}, // 送检数量
                                                            }

                                                        },
                                                        new List<object> //失重
                                                        {
                                                            0,
                                                            "virtual_27",//可以重复，但不能没有？
                                                            new Dictionary<string, object>
                                                            {
                                                                //{"sequence", 4},  //行号，没什么用，加了也是新增在最后一行
                                                                {"inspect_type_id", readOrWrite["WhiteInspectType13"]}, // 检测类型
                                                                {"oqc_ok", readOrWrite["WhiteInspectOQC13"].ToString() == "1" ? true : false}, // OQC标记
                                                                {"qc_level", readOrWrite["WhiteInspectQClevel13"]}, // QC等级
                                                                {"sample_qty", readOrWrite["WhiteInspectSampleQty13"]}, // 送检数量
                                                            }

                                                        },
                                                    }

                        },
                };
                param.Add(new List<object> { (int)id["id"], vals });
            }
            else  //修改毛坯
            {
                var vals = new Dictionary<string, object>
                {
                    //{ "name", readOrWrite.Name },  // 还不能轻易修改产品代码
                    { "atmcn_blueprint_no", readOrWrite["AtmcnBlueprintNo"] },  // 修改安泰图纸号（已成功）
                    //{ "grade", 64 },  // 修改性能，目前只能通过变更修改
                    { "part_name", readOrWrite["PartName"] },  // 修改零件名称/SAP（已成功）
                    { "part_no", readOrWrite["PartNo"] },  // 修改零件号/组装号（已成功）
                    { "product_remark", readOrWrite["ProductRemark"] },  // 修改产品备注（已成功）
                    { "experimental", readOrWrite["Exterimental"].ToString() == "1" ? true : false },  // 修改实验产品（已成功）磁云平台中传回的是"1"，
                    { "blank_for_sale_ok", readOrWrite["BlankForSaleOk"].ToString() == "1" ? true : false },  // 修改毛坯发货
                    { "application", ApplicationCode},  // 修改应用类型（已成功）应用类型上传的是ID
                    { "byproduct_top_ids", byproductTopIdsArray },  // 修改产出其他产品（已成功）
                    { "share_top_ids", shareTopIdsArray },  // 修改共享库存工艺单（已成功）
                    { "plant_ids", plantIds.Count == 2 ? array2D :plantIds[0].ToString() == "宁波工厂" ? array1D1 : array1D2},  // 修改所属工厂（已成功）
                    { "oem_product_ok", readOrWrite["OemProductOk"].ToString() == "1" ? true : false },  // 修改OEM产品 （已成功）
                    { "recycle_flag", readOrWrite["RecycleFlg"].ToString() == "1" ? true : false },  // 修改再循环材料制作（已成功）
                    { "original_product_code", readOrWrite["OriginalProductCode"] },  // 修改原发产品代码（已成功）
                    { "remark_cipianjiao", readOrWrite["RemarkCipianjiao"] },  // 修改磁偏角要求（已成功）

                    { "weight_g", readOrWrite["Weight"] },  // 修改单重（已成功）
                    { "surface_area", readOrWrite["SurfaceArea"] },  // 修改表面积（已成功）

                    { "remark_cailiao", readOrWrite["RemarkCailiao"] },  // 修改出货要求（已成功）
                    { "remark_packaging", readOrWrite["RemarkPackaging"] },  // 修改出货要求（已成功）
                    { "material_grade", readOrWrite["MaterialGrade"] },  // 修改材料性能（已成功）
                    { "steelgrade_id", readOrWrite["SteelGradeId"] },  // 修改钢号
                    { "sintering_type", readOrWrite["SinteringType"] },  // 修改烧结工艺
                    
                    { "geo_tol_lines", CreateGeoTolLines(readOrWrite) }, //修改产品-形位公差

                    { "blank_test_ids", new List<object>   //修改毛坯检测项目（目前添加2个 
                                                {
                                                    new List<object>
                                                    {
                                                        0,
                                                        "virtual_27",//可以重复，但不能没有？
                                                        new Dictionary<string, object>  //添加1个工作中心
                                                        {
                                                            {"inspect_type_id", 14}, // 毛坯检验：B-H曲线检测
                                                            {"oqc_ok", readOrWrite["BlankInspectOQC1"].ToString() == "1" ? true : false}, // OQC标记
                                                            {"qc_level", readOrWrite["BlankInspectQClevel1"]}, // QC等级
                                                            {"sample_qty", readOrWrite["BlankInspectSampleQty1"]}, // 送检数量
                                                        }

                                                    },
                                                    new List<object>
                                                    {
                                                        0,
                                                        "virtual_27",//可以重复，但不能没有？
                                                        new Dictionary<string, object>  //添加1个工作中心
                                                        {
                                                            {"inspect_type_id", 38}, // 毛坯检验：毛坯外观
                                                            //{"oqc_ok", readOrWrite["BlankInspectOQC1"].ToString() == "1" ? true : false}, // OQC标记
                                                            {"qc_level", readOrWrite["BlankInspectQClevel2"]}, // QC等级
                                                            //{"sample_qty", readOrWrite["BlankInspectSampleQty1"]}, // 送检数量
                                                        }

                                                    },

                                                }

                    }
                };
                param.Add(new List<object> { (int)id["id"], vals });
            }

            var vals2 = new Dictionary<string, object>
            {
                { "specification", new Dictionary<string, object>() },
            };
            //param.Add(vals2);
            JObject data = null;
            try
            {
                //整体内容的修改/添加
                data = await Call_BeiFang("object", "execute_kw", param);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"获取aMES数据失败，请求内容：{JsonConvert.SerializeObject(param)}，错误信息：{ex.Message}");
                throw new AppException(ex.ToString());
            }
            var r = new List<object>();
            if (name.Contains("Z"))
            {
                //获得加工页卡的id信息  修改多个加工工序中的内容（尺寸目前无法添加）
                object r1 = await CallRead_Product_BeiFang(name);// 返回的是匿名类型，但被装箱成 object
                dynamic result = r1;   // 拆箱成 dynamic 访问属性
                dynamic rows = result.rows[0];
                List<int> machiningSheetIds = rows.MachiningSheetIds;  //加工工序ids
                List<int> permeationSheetIds = rows.PermeationSheetIds;  //渗透工序ids
                List<int> platingSheetIds = rows.PlatingSheetIds;  //电镀工序ids
                List<List<object>> blankTestIdsNames = rows.BlankTestIdsNames; //毛坯测试ids及displaynames
                List<List<object>> whiteTestIdsNames = rows.WhiteTestIdsNames; //白片测试ids及displaynames
                List<List<object>> platingSheetIdsNames = rows.PlatingSheetIdsNames; //电镀ids及displaynames
                                                                                     //再通过id，获得res_ids信息
                                                                                     //修改加工页卡下的信息
                for (int i = 0; i < machiningSheetIds.Count; i++)  //先选加工类型，再选价格表项，价格表项id为1的会报错不存在，需要选无心磨等对应的
                {
                    var singleResult = await Call_Button_BeiFang("atm.plm.sheet", machiningSheetIds[i]);
                    int res_id = (int)singleResult["result"]["res_id"];
                    string res_model = (string)singleResult["result"]["res_model"];

                    var vals3 = new Dictionary<string, object>
                    {
                        { "pass_rate", readOrWrite["PassRate1"] },  // 合格率
                        { "penalty_pass_rate", readOrWrite["PenaltyPassRate1"] },  // 惩罚合格率
                        { "area", readOrWrite["Area1"] },  // 面积
                        { "workunit_catalog_id", readOrWrite["WorkunitCatalogId1"] },  // 
                        { "square_unit_price_id", readOrWrite["SquareUnitPriceId1"] },  // 
                        { "geo_tol_lines", new List<object>
                                                {
                                                    new List<object>
                                                    {
                                                        0,
                                                        "virtual_23",//不可以重复，不能没有
                                                        new Dictionary<string, object>  //添加1个
                                                        {
                                                            {"geo_type", readOrWrite["GeoType1_1"]}, //
                                                            {"value", readOrWrite["GeoValue1_1"]}, //
                                                        }
                                                    },
                                                    new List<object>
                                                    {
                                                        0,
                                                        "virtual_24",//
                                                        new Dictionary<string, object>  //添加1个
                                                        {
                                                            {"geo_type", readOrWrite["GeoType1_2"]}, //
                                                            {"value", readOrWrite["GeoValue1_2"]}, //
                                                        }
                                                    },
                                                    new List<object>
                                                    {
                                                        0,
                                                        "virtual_25",
                                                        new Dictionary<string, object>  //添加1个
                                                        {
                                                            {"geo_type", readOrWrite["GeoType1_3"]}, //
                                                            {"value", readOrWrite["GeoValue1_3"]}, //
                                                        }
                                                    }

                                                }

                    },
                    };
                    //修改加工里的详细内容
                    await Write_jiagong_BeiFang(res_model, res_id, vals3);
                }
                //修改渗透页卡下的信息
                for (int i = 0; i < permeationSheetIds.Count; i++)
                {
                    var singleResult = await Call_Button_BeiFang("atm.plm.sheet", permeationSheetIds[i]);
                    int res_id = (int)singleResult["result"]["res_id"];
                    string res_model = (string)singleResult["result"]["res_model"];

                    var vals3 = new Dictionary<string, object>
                    {
                        { "magnetic", readOrWrite["Magnetic"] },  // 磁性能性能要求
                    };
                    //修改加工里的详细内容
                    await Write_jiagong_BeiFang(res_model, res_id, vals3);
                }
                //修改电镀页卡下的信息
                for (int i = 0; i < platingSheetIdsNames.Count; i++)
                {
                    switch ((string)platingSheetIdsNames[i][1])
                    {
                        case "倒角R角":
                            var chamferResult = await Call_Button_BeiFang("atm.plm.sheet", (int)platingSheetIdsNames[i][0]);
                            int chamfer_res_id = (int)chamferResult["result"]["res_id"];
                            string chamfer_res_model = (string)chamferResult["result"]["res_model"];
                            var chamfer_vals = new Dictionary<string, object> { };
                            chamfer_vals = new Dictionary<string, object>
                            {
                                { "chamfer_requirements", readOrWrite["ChamferRequirements"] },  // 倒角要求
                            };

                            await Write_jiagong_BeiFang(chamfer_res_model, chamfer_res_id, chamfer_vals);
                            break;

                        case "镀锌":
                            var duxinResult = await Call_Button_BeiFang("atm.plm.sheet", (int)platingSheetIdsNames[i][0]);
                            int duxin_res_id = (int)duxinResult["result"]["res_id"];
                            string duxin_res_model = (string)duxinResult["result"]["res_model"];
                            var duxin_vals = new Dictionary<string, object> { };
                            duxin_vals = new Dictionary<string, object>
                            {
                                { "pass_rate", readOrWrite["PassRate2"]},  //镀锌合格率
                            };

                            await Write_jiagong_BeiFang(duxin_res_model, duxin_res_id, duxin_vals);
                            break;

                        default:
                            Console.WriteLine($"无需编辑检测类型：{platingSheetIdsNames[i][1]}");
                            break;
                    }

                }
                //修改质量-毛坯检验-BH曲线中的信息
                for (int i = 0; i < blankTestIdsNames.Count; i++)
                {
                    if ((string)blankTestIdsNames[i][1] == "B-H曲线")
                    {
                        Console.WriteLine($"找到BH曲线检测的id了！是：{blankTestIdsNames[i][0]}");
                        var singleResult = await Call_Button_BeiFang("atm.plm.top.inspect", (int)blankTestIdsNames[i][0]);
                        int res_id = (int)singleResult["result"]["res_id"];
                        string res_model = (string)singleResult["result"]["res_model"];
                        //再通过res_id获取常温的id，写到下面
                        var qPage = new { context = new { lang = "zh_CN", tz = "Asia/Shanghai" }, limit = 10000, offset = 0 };
                        var qDomain = new List<object> { res_id };
                        var qFields = new List<string> { }; //传过去一个空的，那边的方法再写一个字典
                        var resp = await CallRead_BeiFang("atm.qc.inspect.bh.spec", qDomain, qFields, qPage);
                        int tem_id = 0;
                        foreach (var item in resp["result"][0]["lines"])
                        {
                            if ((string)item["name"] == "常温")
                            {
                                tem_id = (int)item["id"];
                                break;
                            }
                        }

                        var vals3 = new Dictionary<string, object>
                    {
                        { "lines", new List<object>
                        {
                            new List<object>
                            {
                                                1,
                                                tem_id,//常温id,
                                                new Dictionary<string, object>
                                                {
                                                    {"temperature", readOrWrite["BH_Temperature"]},
                                                    {"br", readOrWrite["BH_br_range"]},
                                                    {"hcb", readOrWrite["BH_hcb_range"]},
                                                    {"hcj", readOrWrite["BH_hcj_range"]},
                                                    {"bh", readOrWrite["BH_bh_range"]},
                                                    {"hk", readOrWrite["BH_hk_range"]},
                                                    {"hd5", readOrWrite["BH_hd5_range"]},
                                                    {"percent", readOrWrite["BH_percent_range"]},
                                                }
                            }
                        }


                        }


                    };
                        await Write_jiagong_BeiFang(res_model, res_id, vals3);

                    }
                    else if ((string)blankTestIdsNames[i][1] == "毛坯外观")
                    {
                        Console.WriteLine($"找到毛坯外观检测的id了！是：{blankTestIdsNames[i][0]}");
                        var singleResult = await Call_Button_BeiFang("atm.plm.top.inspect", (int)blankTestIdsNames[i][0]);
                        int res_id = (int)singleResult["result"]["res_id"];
                        string res_model = (string)singleResult["result"]["res_model"];


                        var vals3 = new Dictionary<string, object>
                    {
                        {"requirement", readOrWrite["BlankAppearRequirement"]},
                    };
                        await Write_jiagong_BeiFang(res_model, res_id, vals3);
                    }
                }
                //    //修改质量-白片检验中的信息
                for (int i = 0; i < whiteTestIdsNames.Count; i++)
                {

                    switch ((string)whiteTestIdsNames[i][1])
                    {
                        case "镀层厚度":
                            Console.WriteLine($"找到镀层厚度检测的id了！是：{whiteTestIdsNames[i][0]}");
                            var platingResult = await Call_Button_BeiFang("atm.plm.top.inspect", (int)whiteTestIdsNames[i][0]);
                            int platingResId = (int)platingResult["result"]["res_id"];
                            string platingResModel = (string)platingResult["result"]["res_model"];
                            var platingVals = new Dictionary<string, object>
                            {
                                {"thickness_value_max", readOrWrite["PlatingThicknessMax"]},
                                {"thickness_value_min", readOrWrite["PlatingThicknessMin"]},
                                {"thickness_level1", readOrWrite["ThicknessFirst"]},
                                {"thickness_level2", readOrWrite["ThicknessSecond"]},
                                {"thickness_level3", readOrWrite["ThicknessThird"]}
                            };
                            await Write_jiagong_BeiFang(platingResModel, platingResId, platingVals);
                            break;

                        case "磁通":
                            Console.WriteLine($"找到磁通检测的id了！是：{whiteTestIdsNames[i][0]}");
                            var fluxResult = await Call_Button_BeiFang("atm.plm.top.inspect", (int)whiteTestIdsNames[i][0]);
                            int fluxResId = (int)fluxResult["result"]["res_id"];
                            string fluxResModel = (string)fluxResult["result"]["res_model"];
                            var fluxVals = new Dictionary<string, object>
                            {
                                {"magnetic_flux_value", readOrWrite["MagneticFluxValue"]},
                                {"magnetic_flux_up", readOrWrite["MagneticFluxUp"]},
                                {"magnetic_flux_down", readOrWrite["MagneticFluxDown"]},
                                {"surface_up", readOrWrite["SurfaceUp"]},
                                {"surface_down", readOrWrite["SurfaceDown"]},
                                {"one_hours", readOrWrite["OneHours"]},
                                {"one_temperature", readOrWrite["OneTemperature"]},
                                {"one_baking_con", readOrWrite["OneBakingCon"]},
                                {"magnetic_flux_remark", readOrWrite["MagneticFluxRemark"]},
                            };
                            await Write_jiagong_BeiFang(fluxResModel, fluxResId, fluxVals);
                            break;

                        case "盐雾":
                            Console.WriteLine($"找到盐雾检测的id了！是：{whiteTestIdsNames[i][0]}");
                            var saltResult = await Call_Button_BeiFang("atm.plm.top.inspect", (int)whiteTestIdsNames[i][0]);
                            int saltResId = (int)saltResult["result"]["res_id"];
                            string saltResModel = (string)saltResult["result"]["res_model"];
                            var saltVals = new Dictionary<string, object>
                            {
                                {"salt_mist_condition", readOrWrite["SaltMistCondition"]},
                                {"salt_mist_time", readOrWrite["SaltMistTime"]},
                                {"salt_mist_remark", readOrWrite["SaltMistRemark"]},
                            };
                            await Write_jiagong_BeiFang(saltResModel, saltResId, saltVals);
                            break;

                        case "表面张力":
                            Console.WriteLine($"找到表面张力检测的id了！是：{whiteTestIdsNames[i][0]}");
                            var surfaceResult = await Call_Button_BeiFang("atm.plm.top.inspect", (int)whiteTestIdsNames[i][0]);
                            int surfaceResId = (int)surfaceResult["result"]["res_id"];
                            string surfaceResModel = (string)surfaceResult["result"]["res_model"];
                            var surfaceVals = new Dictionary<string, object>
                            {
                                {"surface_tension_condition", readOrWrite["SurfaceTensionCondition"]},
                                {"surface_tension_value_liquid", readOrWrite["SurfaceTensionValueLiquid"]},
                                {"surface_tension_remark", readOrWrite["SurfaceTensionRemark"]},
                            };
                            await Write_jiagong_BeiFang(surfaceResModel, surfaceResId, surfaceVals);
                            break;

                        case "胶带测试":
                            Console.WriteLine($"找到表面张力检测的id了！是：{whiteTestIdsNames[i][0]}");
                            var tapeResult = await Call_Button_BeiFang("atm.plm.top.inspect", (int)whiteTestIdsNames[i][0]);
                            int tapeResId = (int)tapeResult["result"]["res_id"];
                            string tapeResModel = (string)tapeResult["result"]["res_model"];
                            var tapeVals = new Dictionary<string, object>
                            {
                                {"tape_remark", readOrWrite["TapeRemark"]},
                            };
                            await Write_jiagong_BeiFang(tapeResModel, tapeResId, tapeVals);
                            break;

                        case "湿热":
                            Console.WriteLine($"找到表面张力检测的id了！是：{whiteTestIdsNames[i][0]}");
                            var dampResult = await Call_Button_BeiFang("atm.plm.top.inspect", (int)whiteTestIdsNames[i][0]);
                            int dampResId = (int)dampResult["result"]["res_id"];
                            string dampResModel = (string)dampResult["result"]["res_model"];
                            var dampVals = new Dictionary<string, object>
                            {
                                {"damp_heat_condition", readOrWrite["DampHeatCondition"]},
                                {"damp_heat_remark", readOrWrite["DampHeatRemark"]},
                            };
                            await Write_jiagong_BeiFang(dampResModel, dampResId, dampVals);
                            break;

                        case "PCT":
                            Console.WriteLine($"找到表面张力检测的id了！是：{whiteTestIdsNames[i][0]}");
                            var pctResult = await Call_Button_BeiFang("atm.plm.top.inspect", (int)whiteTestIdsNames[i][0]);
                            int pctResId = (int)pctResult["result"]["res_id"];
                            string pctResModel = (string)pctResult["result"]["res_model"];
                            var pctVals = new Dictionary<string, object>
                            {
                                {"pct_condition", readOrWrite["PctCondition"]},
                                {"pct_remark", readOrWrite["PctRemark"]},
                                {"pct_time", readOrWrite["PctTime"]},
                            };
                            await Write_jiagong_BeiFang(pctResModel, pctResId, pctVals);
                            break;

                        case "光泽度":
                            Console.WriteLine($"找到光泽度检测的id了！是：{whiteTestIdsNames[i][0]}");
                            var glossResult = await Call_Button_BeiFang("atm.plm.top.inspect", (int)whiteTestIdsNames[i][0]);
                            int glossResId = (int)glossResult["result"]["res_id"];
                            string glossResModel = (string)glossResult["result"]["res_model"];
                            var glossVals = new Dictionary<string, object>
                            {
                                {"value_max", readOrWrite["GlossValueMax"]},
                                {"value_min", readOrWrite["GlossValueMin"]},
                            };
                            await Write_jiagong_BeiFang(glossResModel, glossResId, glossVals);
                            break;

                        case "表面烘烤":
                            Console.WriteLine($"找到光泽度检测的id了！是：{whiteTestIdsNames[i][0]}");
                            var bakeMistResult = await Call_Button_BeiFang("atm.plm.top.inspect", (int)whiteTestIdsNames[i][0]);
                            int bakeMistResId = (int)bakeMistResult["result"]["res_id"];
                            string bakeMistResModel = (string)bakeMistResult["result"]["res_model"];
                            var bakeMistVals = new Dictionary<string, object>
                            {
                                {"bake_mist_time", readOrWrite["BakeMistTime"]},
                                {"bake_mist_remark", readOrWrite["BakeMistRemark"]},
                            };
                            await Write_jiagong_BeiFang(bakeMistResModel, bakeMistResId, bakeMistVals);
                            break;

                        case "失重":
                            Console.WriteLine($"找到光泽度检测的id了！是：{whiteTestIdsNames[i][0]}");
                            var lostResult = await Call_Button_BeiFang("atm.plm.top.inspect", (int)whiteTestIdsNames[i][0]);
                            int lostResId = (int)lostResult["result"]["res_id"];
                            string lostResModel = (string)lostResult["result"]["res_model"];
                            var lostVals = new Dictionary<string, object>
                            {
                                {"lost_condition", readOrWrite["LostCondition"]},
                                {"lost_time", readOrWrite["LostTime"]},
                                {"lost_standard_val", readOrWrite["LostStandardVal"]},
                                {"lost_remark", readOrWrite["LostRemark"]},
                            };
                            await Write_jiagong_BeiFang(lostResModel, lostResId, lostVals);
                            break;

                        case "丙酮擦拭":
                            Console.WriteLine($"找到光泽度检测的id了！是：{whiteTestIdsNames[i][0]}");
                            var aceToneWipeResult = await Call_Button_BeiFang("atm.plm.top.inspect", (int)whiteTestIdsNames[i][0]);
                            int aceToneWipeResId = (int)aceToneWipeResult["result"]["res_id"];
                            string aceToneWipeResModel = (string)aceToneWipeResult["result"]["res_model"];
                            var aceToneWipeVals = new Dictionary<string, object>
                            {
                                {"acetone_wipe_remark", readOrWrite["AceToneWipeRemark"]},
                            };
                            await Write_jiagong_BeiFang(aceToneWipeResModel, aceToneWipeResId, aceToneWipeVals);
                            break;

                        case "百格":
                            Console.WriteLine($"找到光泽度检测的id了！是：{whiteTestIdsNames[i][0]}");
                            var crossCutResult = await Call_Button_BeiFang("atm.plm.top.inspect", (int)whiteTestIdsNames[i][0]);
                            int crossCutResId = (int)crossCutResult["result"]["res_id"];
                            string crossCutResModel = (string)crossCutResult["result"]["res_model"];
                            var crossCutVals = new Dictionary<string, object>
                            {
                                {"cross_cut_remark", readOrWrite["CrossCutRemark"]},
                            };
                            await Write_jiagong_BeiFang(crossCutResModel, crossCutResId, crossCutVals);
                            break;

                        case "剪切力":
                            Console.WriteLine($"找到剪切力检测的id了！是：{whiteTestIdsNames[i][0]}");
                            var shearForceResult = await Call_Button_BeiFang("atm.plm.top.inspect", (int)whiteTestIdsNames[i][0]);
                            int shearForceResId = (int)shearForceResult["result"]["res_id"];
                            string shearForceResModel = (string)shearForceResult["result"]["res_model"];
                            var shearForceVals = new Dictionary<string, object>
                            {
                                {"shear_force_remark", readOrWrite["ShearForceRemark"]},
                                {"shear_force_min", readOrWrite["ShearForceMin"]},
                                {"shear_force_max", readOrWrite["ShearForceMax"]},
                            };
                            await Write_jiagong_BeiFang(shearForceResModel, shearForceResId, shearForceVals);
                            break;

                        case "尺寸录入":
                        case "外观检测":
                        case "简单外观检测":
                            Console.WriteLine($"找到3类默认白片检测的id了！是：{whiteTestIdsNames[i][0]}");
                            var param1 = new List<object>();
                            param1.Add(db_beifang);
                            if (uid == null || uid == 0)
                                uid = await GetOdooUid_BeiFang(userName_beifang, password_beifang);
                            param1.Add(uid);
                            param1.Add(password_beifang);
                            param1.Add("atm.plm.top");
                            param1.Add("write");  //web_save  write都可以修改参数，write不需要传入specification参数
                            var vals3 = new Dictionary<string, object>
                            {
                                 { "white_test_ids", new List<object>  //修改白片检测项目
                                                {
                                                    new List<object> //镀层厚度检测
                                                    {
                                                        1,
                                                        (int)whiteTestIdsNames[i][0],
                                                        new Dictionary<string, object>
                                                        {
                                                            {"qc_level", readOrWrite["WhiteInspectSizeInputQCLevel"]}, // 检测类型
                                                            {"sample_qty", readOrWrite["WhiteInspectSizeInputSampleQty"]}, // 送检数量
                                                        }

                                                    },
                                                }

                                 },
                            };
                            param1.Add(new List<object> { (int)id["id"], vals3 });
                            data = await Call_BeiFang("object", "execute_kw", param1);
                            break;

                        default:
                            Console.WriteLine($"无需编辑检测类型：{whiteTestIdsNames[i][1]}");
                            break;
                    }
                }
            }
            // 修改毛坯检测中的内容
            else
            {
                object r1 = await CallRead_Product_BeiFang(name);// 返回的是匿名类型，但被装箱成 object
                dynamic result = r1;   // 拆箱成 dynamic 访问属性
                dynamic rows = result.rows[0];
                List<int> machiningSheetIds = rows.MachiningSheetIds;  //加工工序ids
                List<int> permeationSheetIds = rows.PermeationSheetIds;  //渗透工序ids
                List<int> platingSheetIds = rows.PlatingSheetIds;  //电镀工序ids
                List<List<object>> blankTestIdsNames = rows.BlankTestIdsNames; //毛坯测试ids及displaynames

                //修改质量-毛坯检验-BH曲线中的信息
                for (int i = 0; i < blankTestIdsNames.Count; i++)
                {
                    if ((string)blankTestIdsNames[i][1] == "B-H曲线")
                    {
                        Console.WriteLine($"找到BH曲线检测的id了！是：{blankTestIdsNames[i][0]}");
                        var singleResult = await Call_Button_BeiFang("atm.plm.top.inspect", (int)blankTestIdsNames[i][0]);
                        int res_id = (int)singleResult["result"]["res_id"];
                        string res_model = (string)singleResult["result"]["res_model"];
                        //再通过res_id获取常温的id，写到下面
                        var qPage = new { context = new { lang = "zh_CN", tz = "Asia/Shanghai" }, limit = 10000, offset = 0 };
                        var qDomain = new List<object> { res_id };
                        var qFields = new List<string> { }; //传过去一个空的，那边的方法再写一个字典
                        var resp = await CallRead_BeiFang("atm.qc.inspect.bh.spec", qDomain, qFields, qPage);
                        int tem_id = 0;
                        foreach (var item in resp["result"][0]["lines"])
                        {
                            if ((string)item["name"] == "常温")
                            {
                                tem_id = (int)item["id"];
                                break;
                            }
                        }

                        var vals3 = new Dictionary<string, object>
                    {
                        { "lines", new List<object>
                        {
                            new List<object>
                            {
                                                1,
                                                tem_id,//常温id,
                                                new Dictionary<string, object>
                                                {
                                                    {"temperature", readOrWrite["BH_Temperature"]},
                                                    {"br", readOrWrite["BH_br_range"]},
                                                    {"hcb", readOrWrite["BH_hcb_range"]},
                                                    {"hcj", readOrWrite["BH_hcj_range"]},
                                                    {"bh", readOrWrite["BH_bh_range"]},
                                                    {"hk", readOrWrite["BH_hk_range"]},
                                                    {"hd5", readOrWrite["BH_hd5_range"]},
                                                    {"percent", readOrWrite["BH_percent_range"]},
                                                }
                            }
                        }


                        }


                    };
                        await Write_jiagong_BeiFang(res_model, res_id, vals3);

                    }
                    else if ((string)blankTestIdsNames[i][1] == "毛坯外观")
                    {
                        Console.WriteLine($"找到毛坯外观检测的id了！是：{blankTestIdsNames[i][0]}");
                        var singleResult = await Call_Button_BeiFang("atm.plm.top.inspect", (int)blankTestIdsNames[i][0]);
                        int res_id = (int)singleResult["result"]["res_id"];
                        string res_model = (string)singleResult["result"]["res_model"];


                        var vals3 = new Dictionary<string, object>
                    {
                        {"requirement", readOrWrite["BlankAppearRequirement"]},
                    };
                        await Write_jiagong_BeiFang(res_model, res_id, vals3);
                    }
                }
            }
            

            Console.WriteLine(data);

            return new
            {
                rows = r,
                total = r.Count
            };
        }

        //public async Task<object> CallWrite_Product_BeiFang(string name, ReadOrWrite readOrWrite)
        //{
        //    //先通过另一个接口获取该产品代码ID
        //    if (name?.Length < 7 | name == null)
        //    {
        //        return new
        //        {
        //            rows = new List<string>(),
        //            total = 0
        //        };
        //    }
        //    var id = (JObject)await SyncProduction_BF(name);
        //    if (id == null)
        //    {
        //        return null;
        //    }

        //    Console.WriteLine("wwwwww");
        //    var param = new List<object>();
        //    param.Add(db_beifang);
        //    if (uid == null || uid == 0)
        //        uid = await GetOdooUid_BeiFang(userName_beifang, password_beifang);
        //    param.Add(uid);
        //    param.Add(password_beifang);
        //    param.Add("atm.plm.top");//修改产品工艺单中的内容模型
        //    //param.Add("write");
        //    //(    db, uid, password, 'atm.plm.top', 'web_save',
        //    //[ [id],{"product_remark":"234"} ], { "specification":{ } }    )   python版本
        //    //param.Add("web_save");
        //    param.Add("write");  //web_save  write都可以修改参数，write不需要传入specification参数
        //    var applicationMapping = new Dictionary<string, int>
        //    {
        //        ["工业电机"] = 6,
        //        ["喇叭音响"] = 7,
        //        ["汽车车载"] = 8,
        //        ["消费品电子"] = 9,
        //        ["其他"] = 10,
        //        ["直线电机"] = 11,
        //        ["电动自行车"] = 12,
        //        ["车载汽车"] = 13
        //    };
        //    int[,] array2D = new int[2, 2] { { 4, 1 }, { 4, 2 } };  //添加是41  42 添加宁波和D座 删除是31  32 4是新增的意思，3是删除的意思
        //    int[,] array1D1 = new int[1, 2] { { 4, 1 } };  //添加宁波工厂
        //    int[,] array1D2 = new int[1, 2] { { 4, 2 } };  //添加是D座

        //    int[][] byproductTopIdsArray = ConvertListToJaggedArray(readOrWrite.ByproductTopIds);
        //    int[][] shareTopIds = ConvertListToJaggedArray(readOrWrite.ShareTopIds);
        //    //修改成品
        //    if (readOrWrite.Name.Contains("Z"))
        //    {  //修改成品
        //        var vals = new Dictionary<string, object>
        //    {
        //        //{ "name", readOrWrite.Name },  // 还不能轻易修改产品代码
        //        { "atmcn_blueprint_no", readOrWrite.AtmcnBlueprintNo },  // 修改安泰图纸号（已成功）
        //        //{ "grade", 64 },  // 修改性能，目前只能通过变更修改
        //        { "part_name", readOrWrite.PartName },  // 修改零件名称/SAP（已成功）
        //        { "part_no", readOrWrite.PartNo },  // 修改零件号/组装号（已成功）
        //        { "product_remark", readOrWrite.ProductRemark },  // 修改产品备注（已成功）
        //        { "experimental", readOrWrite.Exterimental == "1" ? true : false },  // 修改实验产品（已成功）磁云平台中传回的是"1"，
        //        { "application", applicationMapping.TryGetValue(readOrWrite.Application?.ToString() ?? "", out var value)? value: 0},  // 修改应用类型（已成功）应用类型上传的是ID
        //        { "plant_ids", readOrWrite.PlantIds.Count == 2 ? array2D :(readOrWrite.PlantIds[0] == "宁波工厂" ? array1D1 : array1D2)},  // 修改所属工厂（已成功）
        //        { "weight_g", readOrWrite.Weight },  // 修改单重（已成功）
        //        { "surface_area", readOrWrite.SurfaceArea },  // 修改表面积（已成功）
        //        { "remark_cailiao", readOrWrite.RemarkCailiao },  // 修改材料其他要求（已成功）
        //        { "grade_after_permeation", readOrWrite.GradeAfterPermeation },  // 修改渗透后磁性能（已成功）
        //        { "daojiao_id", readOrWrite.DaojiaoId },  // 修改渗透后磁性能（已成功）
        //        { "ducenghoudu_id", readOrWrite.DucenghouduId },  // 修改渗透后磁性能（已成功）
        //        { "remark_diandu", readOrWrite.RemarkDiandu },  // 修改渗透后磁性能（已成功）
        //        { "qty_per_chest", readOrWrite.QtyPerChest },  // 修改每箱数量（已成功）
        //        { "qty_per_box", readOrWrite.QtyPerBox },  // 修改每盒数量（已成功）
        //        { "qty_per_bag", readOrWrite.QtyPerBag },  // 修改每袋数量（已成功）
        //        { "byproduct_top_ids", byproductTopIdsArray },  // 修改产出其他产品（已成功）
        //        { "share_top_ids", shareTopIds },  // 修改共享库存工艺单（已成功）
        //        { "material_grade", readOrWrite.MaterialGrade },  // 修改材料性能（已成功）
        //        { "steelgrade_id", readOrWrite.SteelGradeId },  // 修改
        //        { "sintering_type", readOrWrite.SinteringType },  // 修改
        //        { "permeation_gongyi_id", readOrWrite.PermeationGongyiId },  // 修改渗透工艺
        //        { "machining_sheet_ids", new List<object>  //修改加工工序-车间类型、工作中心（目前只添加1个）
        //                                    {
        //                                        new List<object>
        //                                        {
        //                                            0,
        //                                            "virtual_23",//可以重复，但不能没有？
        //                                            new Dictionary<string, object>  //添加1个工作中心
        //                                            {
        //                                                //{"sequence", 4},  //行号，没什么用，加了也是新增在最后一行
        //                                                {"workcenter_type_id", readOrWrite.WorkcenterType1}, //车间类型
        //                                                {"mrp_workcenter_id", readOrWrite.MrpWorkcenter1}, //工作中心
        //                                            }
        //                                        }

        //                                    }

        //        },
        //        { "permeation_sheet_ids", new List<object>  //修改渗透工序-车间类型、工作中心（目前只添加1个）
        //                                    {
        //                                        new List<object>
        //                                        {
        //                                            0,
        //                                            "virtual_24",//可以重复，但不能没有？
        //                                            new Dictionary<string, object>  //添加1个工作中心
        //                                            {
        //                                                //{"sequence", 4},  //行号，没什么用，加了也是新增在最后一行
        //                                                {"workcenter_type_id", readOrWrite.WorkcenterType2}, //车间类型
        //                                                {"mrp_workcenter_id", readOrWrite.MrpWorkcenter2}, //工作中心
        //                                            }
        //                                        }

        //                                    }

        //        },
        //        { "plating_sheet_ids", new List<object>  //修改电镀工序-车间类型、工作中心（目前添加2个）
        //                                    {
        //                                        new List<object>
        //                                        {
        //                                            0,
        //                                            "virtual_25",//可以重复，但不能没有？
        //                                            new Dictionary<string, object>  //添加1个工作中心
        //                                            {
        //                                                //{"sequence", 4},  //行号，没什么用，加了也是新增在最后一行
        //                                                {"workcenter_type_id", readOrWrite.WorkcenterType3}, //车间类型
        //                                                {"mrp_workcenter_id", readOrWrite.MrpWorkcenter3}, //工作中心
        //                                            }

        //                                        },
        //                                        new List<object>
        //                                        {
        //                                            0,
        //                                            "virtual_26",//可以重复，但不能没有？
        //                                            new Dictionary<string, object>  //添加1个工作中心
        //                                            {
        //                                                //{"sequence", 4},  //行号，没什么用，加了也是新增在最后一行
        //                                                {"workcenter_type_id", readOrWrite.WorkcenterType4}, //车间类型
        //                                                {"mrp_workcenter_id", readOrWrite.MrpWorkcenter4}, //工作中心
        //                                            }
        //                                        }

        //                                    }

        //        },
        //        { "blank_test_ids", new List<object>  //修改毛坯检测项目（目前添加1个
        //                                    {
        //                                        new List<object>
        //                                        {
        //                                            0,
        //                                            "virtual_27",//可以重复，但不能没有？
        //                                            new Dictionary<string, object>  //添加1个工作中心
        //                                            {
        //                                                //{"sequence", 4},  //行号，没什么用，加了也是新增在最后一行
        //                                                {"inspect_type_id", readOrWrite.BlankInspectType1}, // 检测类型
        //                                                {"oqc_ok", readOrWrite.BlankInspectOQC1 == "1" ? true : false}, // OQC标记
        //                                                {"qc_level", readOrWrite.BlankInspectQClevel1}, // QC等级
        //                                                {"sample_qty", readOrWrite.BlankInspectSampleQty1}, // 送检数量
        //                                            }

        //                                        }

        //                                    }

        //        },
        //        { "white_test_ids", new List<object>  //修改白片检测项目
        //                                    {
        //                                        new List<object> //镀层厚度检测
        //                                        {
        //                                            0,
        //                                            "virtual_27",//可以重复，但不能没有？
        //                                            new Dictionary<string, object>
        //                                            {
        //                                                //{"sequence", 4},  //行号，没什么用，加了也是新增在最后一行
        //                                                {"inspect_type_id", readOrWrite.WhiteInspectType1}, // 检测类型
        //                                                {"oqc_ok", readOrWrite.WhiteInspectOQC1 == "1" ? true : false}, // OQC标记
        //                                                {"qc_level", readOrWrite.WhiteInspectQClevel1}, // QC等级
        //                                                {"sample_qty", readOrWrite.WhiteInspectSampleQty1}, // 送检数量
        //                                            }

        //                                        },
        //                                        new List<object> //磁通检测
        //                                        {
        //                                            0,
        //                                            "virtual_27",//可以重复，但不能没有？
        //                                            new Dictionary<string, object>
        //                                            {
        //                                                //{"sequence", 4},  //行号，没什么用，加了也是新增在最后一行
        //                                                {"inspect_type_id", readOrWrite.WhiteInspectType2}, // 检测类型
        //                                                {"oqc_ok", readOrWrite.WhiteInspectOQC2 == "1" ? true : false}, // OQC标记
        //                                                {"qc_level", readOrWrite.WhiteInspectQClevel2}, // QC等级
        //                                                {"sample_qty", readOrWrite.WhiteInspectSampleQty2}, // 送检数量
        //                                            }

        //                                        },
        //                                        new List<object> //盐雾检测
        //                                        {
        //                                            0,
        //                                            "virtual_27",//可以重复，但不能没有？
        //                                            new Dictionary<string, object>
        //                                            {
        //                                                //{"sequence", 4},  //行号，没什么用，加了也是新增在最后一行
        //                                                {"inspect_type_id", readOrWrite.WhiteInspectType3}, // 检测类型
        //                                                {"oqc_ok", readOrWrite.WhiteInspectOQC3 == "1" ? true : false}, // OQC标记
        //                                                {"qc_level", readOrWrite.WhiteInspectQClevel3}, // QC等级
        //                                                {"sample_qty", readOrWrite.WhiteInspectSampleQty3}, // 送检数量
        //                                            }

        //                                        },
        //                                        new List<object> //表面张力检测
        //                                        {
        //                                            0,
        //                                            "virtual_27",//可以重复，但不能没有？
        //                                            new Dictionary<string, object>
        //                                            {
        //                                                //{"sequence", 4},  //行号，没什么用，加了也是新增在最后一行
        //                                                {"inspect_type_id", readOrWrite.WhiteInspectType4}, // 检测类型
        //                                                {"oqc_ok", readOrWrite.WhiteInspectOQC4 == "1" ? true : false}, // OQC标记
        //                                                {"qc_level", readOrWrite.WhiteInspectQClevel4}, // QC等级
        //                                                {"sample_qty", readOrWrite.WhiteInspectSampleQty4}, // 送检数量
        //                                            }

        //                                        },
        //                                        new List<object> //胶带检测
        //                                        {
        //                                            0,
        //                                            "virtual_27",//可以重复，但不能没有？
        //                                            new Dictionary<string, object>
        //                                            {
        //                                                //{"sequence", 4},  //行号，没什么用，加了也是新增在最后一行
        //                                                {"inspect_type_id", readOrWrite.WhiteInspectType5}, // 检测类型
        //                                                {"oqc_ok", readOrWrite.WhiteInspectOQC5 == "1" ? true : false}, // OQC标记
        //                                                {"qc_level", readOrWrite.WhiteInspectQClevel5}, // QC等级
        //                                                {"sample_qty", readOrWrite.WhiteInspectSampleQty5}, // 送检数量
        //                                            }

        //                                        },
        //                                        new List<object> //湿热检测
        //                                        {
        //                                            0,
        //                                            "virtual_27",//可以重复，但不能没有？
        //                                            new Dictionary<string, object>
        //                                            {
        //                                                //{"sequence", 4},  //行号，没什么用，加了也是新增在最后一行
        //                                                {"inspect_type_id", readOrWrite.WhiteInspectType6}, // 检测类型
        //                                                {"oqc_ok", readOrWrite.WhiteInspectOQC6 == "1" ? true : false}, // OQC标记
        //                                                {"qc_level", readOrWrite.WhiteInspectQClevel6}, // QC等级
        //                                                {"sample_qty", readOrWrite.WhiteInspectSampleQty6}, // 送检数量
        //                                            }

        //                                        },
        //                                        new List<object> //PCT检测
        //                                        {
        //                                            0,
        //                                            "virtual_27",//可以重复，但不能没有？
        //                                            new Dictionary<string, object>
        //                                            {
        //                                                //{"sequence", 4},  //行号，没什么用，加了也是新增在最后一行
        //                                                {"inspect_type_id", readOrWrite.WhiteInspectType7}, // 检测类型
        //                                                {"oqc_ok", readOrWrite.WhiteInspectOQC7 == "1" ? true : false}, // OQC标记
        //                                                {"qc_level", readOrWrite.WhiteInspectQClevel7}, // QC等级
        //                                                {"sample_qty", readOrWrite.WhiteInspectSampleQty7}, // 送检数量
        //                                            }

        //                                        },
        //                                        new List<object> //PCT检测
        //                                        {
        //                                            0,
        //                                            "virtual_27",//可以重复，但不能没有？
        //                                            new Dictionary<string, object>
        //                                            {
        //                                                //{"sequence", 4},  //行号，没什么用，加了也是新增在最后一行
        //                                                {"inspect_type_id", readOrWrite.WhiteInspectType8}, // 检测类型
        //                                                {"oqc_ok", readOrWrite.WhiteInspectOQC8 == "1" ? true : false}, // OQC标记
        //                                                {"qc_level", readOrWrite.WhiteInspectQClevel8}, // QC等级
        //                                                {"sample_qty", readOrWrite.WhiteInspectSampleQty8}, // 送检数量
        //                                            }

        //                                        },
        //                                        new List<object> //PCT检测
        //                                        {
        //                                            0,
        //                                            "virtual_27",//可以重复，但不能没有？
        //                                            new Dictionary<string, object>
        //                                            {
        //                                                //{"sequence", 4},  //行号，没什么用，加了也是新增在最后一行
        //                                                {"inspect_type_id", readOrWrite.WhiteInspectType9}, // 检测类型
        //                                                {"oqc_ok", readOrWrite.WhiteInspectOQC9 == "1" ? true : false}, // OQC标记
        //                                                {"qc_level", readOrWrite.WhiteInspectQClevel9}, // QC等级
        //                                                {"sample_qty", readOrWrite.WhiteInspectSampleQty9}, // 送检数量
        //                                            }

        //                                        },
        //                                        new List<object> //失重
        //                                        {
        //                                            0,
        //                                            "virtual_27",//可以重复，但不能没有？
        //                                            new Dictionary<string, object>
        //                                            {
        //                                                //{"sequence", 4},  //行号，没什么用，加了也是新增在最后一行
        //                                                {"inspect_type_id", readOrWrite.WhiteInspectType10}, // 检测类型
        //                                                {"oqc_ok", readOrWrite.WhiteInspectOQC10 == "1" ? true : false}, // OQC标记
        //                                                {"qc_level", readOrWrite.WhiteInspectQClevel10}, // QC等级
        //                                                {"sample_qty", readOrWrite.WhiteInspectSampleQty10}, // 送检数量
        //                                            }

        //                                        },
        //                                        new List<object> //失重
        //                                        {
        //                                            0,
        //                                            "virtual_27",//可以重复，但不能没有？
        //                                            new Dictionary<string, object>
        //                                            {
        //                                                //{"sequence", 4},  //行号，没什么用，加了也是新增在最后一行
        //                                                {"inspect_type_id", readOrWrite.WhiteInspectType11}, // 检测类型
        //                                                {"oqc_ok", readOrWrite.WhiteInspectOQC11 == "1" ? true : false}, // OQC标记
        //                                                {"qc_level", readOrWrite.WhiteInspectQClevel11}, // QC等级
        //                                                {"sample_qty", readOrWrite.WhiteInspectSampleQty11}, // 送检数量
        //                                            }

        //                                        },
        //                                        new List<object> //失重
        //                                        {
        //                                            0,
        //                                            "virtual_27",//可以重复，但不能没有？
        //                                            new Dictionary<string, object>
        //                                            {
        //                                                //{"sequence", 4},  //行号，没什么用，加了也是新增在最后一行
        //                                                {"inspect_type_id", readOrWrite.WhiteInspectType12}, // 检测类型
        //                                                {"oqc_ok", readOrWrite.WhiteInspectOQC12 == "1" ? true : false}, // OQC标记
        //                                                {"qc_level", readOrWrite.WhiteInspectQClevel12}, // QC等级
        //                                                {"sample_qty", readOrWrite.WhiteInspectSampleQty12}, // 送检数量
        //                                            }

        //                                        },
        //                                        new List<object> //失重
        //                                        {
        //                                            0,
        //                                            "virtual_27",//可以重复，但不能没有？
        //                                            new Dictionary<string, object>
        //                                            {
        //                                                //{"sequence", 4},  //行号，没什么用，加了也是新增在最后一行
        //                                                {"inspect_type_id", readOrWrite.WhiteInspectType13}, // 检测类型
        //                                                {"oqc_ok", readOrWrite.WhiteInspectOQC13 == "1" ? true : false}, // OQC标记
        //                                                {"qc_level", readOrWrite.WhiteInspectQClevel13}, // QC等级
        //                                                {"sample_qty", readOrWrite.WhiteInspectSampleQty13}, // 送检数量
        //                                            }

        //                                        },
        //                                    }

        //        },
        //    };
        //        param.Add(new List<object> { (int)id["id"], vals });
        //    }
        //    else  //修改毛坯
        //    {
        //        var vals = new Dictionary<string, object>
        //        {
        //            //{ "name", readOrWrite.Name },  // 还不能轻易修改产品代码
        //            { "atmcn_blueprint_no", readOrWrite.AtmcnBlueprintNo },  // 修改安泰图纸号（已成功）
        //            //{ "grade", 64 },  // 修改性能，目前只能通过变更修改
        //            { "part_name", readOrWrite.PartName },  // 修改零件名称/SAP（已成功）
        //            { "part_no", readOrWrite.PartNo },  // 修改零件号/组装号（已成功）
        //            { "product_remark", readOrWrite.ProductRemark },  // 修改产品备注（已成功）
        //            { "experimental", readOrWrite.Exterimental == "1" ? true : false },  // 修改实验产品（已成功）磁云平台中传回的是"1"，
        //            { "application", applicationMapping.TryGetValue(readOrWrite.Application?.ToString() ?? "", out var value)? value: 0},  // 修改应用类型（已成功）应用类型上传的是ID
        //            { "byproduct_top_ids", byproductTopIdsArray },  // 修改产出其他产品（已成功）
        //            { "share_top_ids", shareTopIds },  // 修改共享库存工艺单（已成功）
        //            { "plant_ids", readOrWrite.PlantIds.Count == 2 ? array2D :(readOrWrite.PlantIds[0] == "宁波工厂" ? array1D1 : array1D2)},  // 修改所属工厂（已成功）

        //            { "weight_g", readOrWrite.Weight },  // 修改单重（已成功）
        //            { "surface_area", readOrWrite.SurfaceArea },  // 修改表面积（已成功）

        //            { "remark_cailiao", readOrWrite.RemarkCailiao },  // 修改材料其他要求（已成功）
        //            { "material_grade", readOrWrite.MaterialGrade },  // 修改材料性能（已成功）
        //            { "steelgrade_id", readOrWrite.SteelGradeId },  // 修改钢号
        //            { "sintering_type", readOrWrite.SinteringType },  // 修改烧结工艺
        //            { "blank_test_ids", new List<object>  //修改毛坯检测项目（目前添加1个
        //                                        {
        //                                            new List<object>
        //                                            {
        //                                                0,
        //                                                "virtual_27",//可以重复，但不能没有？
        //                                                new Dictionary<string, object>  //添加1个工作中心
        //                                                {
        //                                                    {"inspect_type_id", readOrWrite.BlankInspectType1}, // 检测类型
        //                                                    {"oqc_ok", readOrWrite.BlankInspectOQC1 == "1" ? true : false}, // OQC标记
        //                                                    {"qc_level", readOrWrite.BlankInspectQClevel1}, // QC等级
        //                                                    {"sample_qty", readOrWrite.BlankInspectSampleQty1}, // 送检数量
        //                                                }

        //                                            }

        //                                        }

        //            }
        //        };
        //        param.Add(new List<object> { (int)id["id"], vals });
        //    }

        //    var vals2 = new Dictionary<string, object>
        //    {
        //        { "specification", new Dictionary<string, object>() },
        //    };
        //    //param.Add(vals2);
        //    JObject data = null;
        //    try
        //    {
        //        //整体内容的修改/添加
        //        data = await Call_BeiFang("object", "execute_kw", param);
        //    }
        //    catch (Exception ex)
        //    {
        //        logger.LogError(ex, $"获取aMES数据失败，请求内容：{JsonConvert.SerializeObject(param)}，错误信息：{ex.Message}");
        //        throw new AppException(ex.ToString());
        //    }
        //    var r = new List<object>();
        //    //获得加工页卡的id信息  修改多个加工工序中的内容（尺寸目前无法添加）
        //    object r1 = await CallRead_Product_BeiFang(name);// 返回的是匿名类型，但被装箱成 object
        //    dynamic result = r1;   // 拆箱成 dynamic 访问属性
        //    dynamic rows = result.rows[0];
        //    List<int> machiningSheetIds = rows.MachiningSheetIds;  //加工工序ids
        //    List<int> permeationSheetIds = rows.PermeationSheetIds;  //渗透工序ids
        //    List<int> platingSheetIds = rows.PlatingSheetIds;  //电镀工序ids
        //    List<List<object>> blankTestIdsNames = rows.BlankTestIdsNames; //毛坯测试ids及displaynames
        //    List<List<object>> whiteTestIdsNames = rows.WhiteTestIdsNames; //白片测试ids及displaynames
        //    List<List<object>> platingSheetIdsNames = rows.PlatingSheetIdsNames; //白片测试ids及displaynames
        //    //再通过id，获得res_ids信息  修改多个加工工序中的内容（尺寸目前无法添加）
        //    //修改加工页卡下的信息
        //    for (int i = 0; i < machiningSheetIds.Count; i++)  //先选加工类型，再选价格表项，价格表项id为1的会报错不存在，需要选无心磨等对应的
        //    {
        //        var singleResult = await Call_Button_BeiFang("atm.plm.sheet", machiningSheetIds[i]);
        //        int res_id = (int)singleResult["result"]["res_id"];
        //        string res_model = (string)singleResult["result"]["res_model"];

        //        var vals3 = new Dictionary<string, object>
        //        {
        //            { "pass_rate", readOrWrite.PassRate1 },  // 合格率
        //            { "penalty_pass_rate", readOrWrite.PenaltyPassRate1 },  // 惩罚合格率
        //            { "area", readOrWrite.Area1 },  // 面积
        //            { "workunit_catalog_id", readOrWrite.WorkunitCatalogId1 },  // 
        //            { "square_unit_price_id", readOrWrite.SquareUnitPriceId1 },  // 
        //            { "geo_tol_lines", new List<object>
        //                                    {
        //                                        new List<object>
        //                                        {
        //                                            0,
        //                                            "virtual_23",//不可以重复，不能没有
        //                                            new Dictionary<string, object>  //添加1个
        //                                            {
        //                                                {"geo_type", readOrWrite.GeoType1_1}, //
        //                                                {"value", readOrWrite.GeoValue1_1}, //
        //                                            }
        //                                        },
        //                                        new List<object>
        //                                        {
        //                                            0,
        //                                            "virtual_24",//
        //                                            new Dictionary<string, object>  //添加1个
        //                                            {
        //                                                {"geo_type", readOrWrite.GeoType1_2}, //
        //                                                {"value", readOrWrite.GeoValue1_2}, //
        //                                            }
        //                                        },
        //                                        new List<object>
        //                                        {
        //                                            0,
        //                                            "virtual_25",
        //                                            new Dictionary<string, object>  //添加1个
        //                                            {
        //                                                {"geo_type", readOrWrite.GeoType1_3}, //
        //                                                {"value", readOrWrite.GeoValue1_3}, //
        //                                            }
        //                                        }

        //                                    }

        //        },
        //        };
        //        //修改加工里的详细内容
        //        await Write_jiagong_BeiFang(res_model, res_id, vals3);
        //    }
        //    //修改渗透页卡下的信息
        //    for (int i = 0; i < permeationSheetIds.Count; i++)
        //    {
        //        var singleResult = await Call_Button_BeiFang("atm.plm.sheet", permeationSheetIds[i]);
        //        int res_id = (int)singleResult["result"]["res_id"];
        //        string res_model = (string)singleResult["result"]["res_model"];

        //        var vals3 = new Dictionary<string, object>
        //        {
        //            { "magnetic", readOrWrite.Magnetic },  // 磁性能性能要求
        //        };
        //        //修改加工里的详细内容
        //        await Write_jiagong_BeiFang(res_model, res_id, vals3);
        //    }
        //    //修改电镀页卡下的信息
        //    for (int i = 0; i < platingSheetIdsNames.Count; i++)
        //    {
        //        switch ((string)platingSheetIdsNames[i][1])
        //        {
        //            case "倒角R角":
        //                var chamferResult = await Call_Button_BeiFang("atm.plm.sheet", (int)platingSheetIdsNames[i][0]);
        //                int chamfer_res_id = (int)chamferResult["result"]["res_id"];
        //                string chamfer_res_model = (string)chamferResult["result"]["res_model"];
        //                var chamfer_vals = new Dictionary<string, object> { };
        //                chamfer_vals = new Dictionary<string, object>
        //                {
        //                    { "chamfer_requirements", readOrWrite.ChamferRequirements },  // 倒角要求
        //                };

        //                await Write_jiagong_BeiFang(chamfer_res_model, chamfer_res_id, chamfer_vals);
        //                break;

        //            case "镀锌":
        //                var duxinResult = await Call_Button_BeiFang("atm.plm.sheet", (int)platingSheetIdsNames[i][0]);
        //                int duxin_res_id = (int)duxinResult["result"]["res_id"];
        //                string duxin_res_model = (string)duxinResult["result"]["res_model"];
        //                var duxin_vals = new Dictionary<string, object> { };
        //                duxin_vals = new Dictionary<string, object>
        //                {
        //                    { "pass_rate", readOrWrite.PassRate2},  //镀锌合格率
        //                };

        //                await Write_jiagong_BeiFang(duxin_res_model, duxin_res_id, duxin_vals);
        //                break;

        //            default:
        //                Console.WriteLine($"无需编辑检测类型：{platingSheetIdsNames[i][1]}");
        //                break;
        //        }

        //    }
        //    //修改质量-毛坯检验-BH曲线中的信息
        //    for (int i = 0; i < blankTestIdsNames.Count; i++)
        //    {
        //        if ((string)blankTestIdsNames[i][1] == "B-H曲线")
        //        {
        //            Console.WriteLine($"找到BH曲线检测的id了！是：{blankTestIdsNames[i][0]}");
        //            var singleResult = await Call_Button_BeiFang("atm.plm.top.inspect", (int)blankTestIdsNames[i][0]);
        //            int res_id = (int)singleResult["result"]["res_id"];
        //            string res_model = (string)singleResult["result"]["res_model"];
        //            //再通过res_id获取常温的id，写到下面
        //            var qPage = new { context = new { lang = "zh_CN", tz = "Asia/Shanghai" }, limit = 10000, offset = 0 };
        //            var qDomain = new List<object> { res_id };
        //            var qFields = new List<string> { }; //传过去一个空的，那边的方法再写一个字典
        //            var resp = await CallRead_BeiFang("atm.qc.inspect.bh.spec", qDomain, qFields, qPage);
        //            int tem_id = 0;
        //            foreach (var item in resp["result"][0]["lines"])
        //            {
        //                if ((string)item["name"] == "常温")
        //                {
        //                    tem_id = (int)item["id"];
        //                    break;
        //                }
        //            }

        //            var vals3 = new Dictionary<string, object>
        //            {
        //                { "lines", new List<object>
        //                {
        //                    new List<object>
        //                    {
        //                                        1,
        //                                        tem_id,//常温id,
        //                                        new Dictionary<string, object>
        //                                        {
        //                                            {"temperature", readOrWrite.BH_Temperature},
        //                                            {"br", readOrWrite.BH_br_range},
        //                                            {"hcb", readOrWrite.BH_hcb_range},
        //                                            {"hcj", readOrWrite.BH_hcj_range},
        //                                            {"bh", readOrWrite.BH_bh_range},
        //                                            {"hk", readOrWrite.BH_hk_range},
        //                                            {"hd5", readOrWrite.BH_hd5_range},
        //                                            {"percent", readOrWrite.BH_percent_range},
        //                                        }
        //                                    }
        //                }


        //                }


        //            };
        //            await Write_jiagong_BeiFang(res_model, res_id, vals3);

        //        }
        //    }
        //    //修改质量-白片检验中的信息
        //    for (int i = 0; i < whiteTestIdsNames.Count; i++)
        //    {

        //        switch ((string)whiteTestIdsNames[i][1])
        //        {
        //            case "镀层厚度":
        //                Console.WriteLine($"找到镀层厚度检测的id了！是：{whiteTestIdsNames[i][0]}");
        //                var platingResult = await Call_Button_BeiFang("atm.plm.top.inspect", (int)whiteTestIdsNames[i][0]);
        //                int platingResId = (int)platingResult["result"]["res_id"];
        //                string platingResModel = (string)platingResult["result"]["res_model"];
        //                var platingVals = new Dictionary<string, object>
        //                {
        //                    {"thickness_value_max", readOrWrite.PlatingThicknessMax},
        //                    {"thickness_value_min", readOrWrite.PlatingThicknessMin},
        //                    {"thickness_level1", readOrWrite.ThicknessFirst},
        //                    {"thickness_level2", readOrWrite.ThicknessSecond},
        //                    {"thickness_level3", readOrWrite.ThicknessThird}
        //                };
        //                await Write_jiagong_BeiFang(platingResModel, platingResId, platingVals);
        //                break;

        //            case "磁通":
        //                Console.WriteLine($"找到磁通检测的id了！是：{whiteTestIdsNames[i][0]}");
        //                var fluxResult = await Call_Button_BeiFang("atm.plm.top.inspect", (int)whiteTestIdsNames[i][0]);
        //                int fluxResId = (int)fluxResult["result"]["res_id"];
        //                string fluxResModel = (string)fluxResult["result"]["res_model"];
        //                var fluxVals = new Dictionary<string, object>
        //                {
        //                    {"magnetic_flux_value", readOrWrite.MagneticFluxValue},
        //                    {"magnetic_flux_up", readOrWrite.MagneticFluxUp},
        //                    {"magnetic_flux_down", readOrWrite.MagneticFluxDown},
        //                    {"surface_up", readOrWrite.SurfaceUp},
        //                    {"surface_down", readOrWrite.SurfaceDown},
        //                    {"one_hours", readOrWrite.OneHours},
        //                    {"one_temperature", readOrWrite.OneTemperature},
        //                    {"one_baking_con", readOrWrite.OneBakingCon},
        //                    {"magnetic_flux_remark", readOrWrite.MagneticFluxRemark},
        //                };
        //                await Write_jiagong_BeiFang(fluxResModel, fluxResId, fluxVals);
        //                break;

        //            case "盐雾":
        //                Console.WriteLine($"找到盐雾检测的id了！是：{whiteTestIdsNames[i][0]}");
        //                var saltResult = await Call_Button_BeiFang("atm.plm.top.inspect", (int)whiteTestIdsNames[i][0]);
        //                int saltResId = (int)saltResult["result"]["res_id"];
        //                string saltResModel = (string)saltResult["result"]["res_model"];
        //                var saltVals = new Dictionary<string, object>
        //                {
        //                    {"salt_mist_condition", readOrWrite.SaltMistCondition},
        //                    {"salt_mist_time", readOrWrite.SaltMistTime},
        //                    {"salt_mist_remark", readOrWrite.SaltMistRemark},
        //                };
        //                await Write_jiagong_BeiFang(saltResModel, saltResId, saltVals);
        //                break;

        //            case "表面张力":
        //                Console.WriteLine($"找到表面张力检测的id了！是：{whiteTestIdsNames[i][0]}");
        //                var surfaceResult = await Call_Button_BeiFang("atm.plm.top.inspect", (int)whiteTestIdsNames[i][0]);
        //                int surfaceResId = (int)surfaceResult["result"]["res_id"];
        //                string surfaceResModel = (string)surfaceResult["result"]["res_model"];
        //                var surfaceVals = new Dictionary<string, object>
        //                {
        //                    {"surface_tension_condition", readOrWrite.SurfaceTensionCondition},
        //                    {"surface_tension_value_liquid", readOrWrite.SurfaceTensionValueLiquid},
        //                    {"surface_tension_remark", readOrWrite.SurfaceTensionRemark},
        //                };
        //                await Write_jiagong_BeiFang(surfaceResModel, surfaceResId, surfaceVals);
        //                break;

        //            case "胶带测试":
        //                Console.WriteLine($"找到表面张力检测的id了！是：{whiteTestIdsNames[i][0]}");
        //                var tapeResult = await Call_Button_BeiFang("atm.plm.top.inspect", (int)whiteTestIdsNames[i][0]);
        //                int tapeResId = (int)tapeResult["result"]["res_id"];
        //                string tapeResModel = (string)tapeResult["result"]["res_model"];
        //                var tapeVals = new Dictionary<string, object>
        //                {
        //                    {"tape_remark", readOrWrite.TapeRemark},
        //                };
        //                await Write_jiagong_BeiFang(tapeResModel, tapeResId, tapeVals);
        //                break;

        //            case "湿热":
        //                Console.WriteLine($"找到表面张力检测的id了！是：{whiteTestIdsNames[i][0]}");
        //                var dampResult = await Call_Button_BeiFang("atm.plm.top.inspect", (int)whiteTestIdsNames[i][0]);
        //                int dampResId = (int)dampResult["result"]["res_id"];
        //                string dampResModel = (string)dampResult["result"]["res_model"];
        //                var dampVals = new Dictionary<string, object>
        //                {
        //                    {"damp_heat_condition", readOrWrite.DampHeatCondition},
        //                    {"damp_heat_remark", readOrWrite.DampHeatRemark},
        //                };
        //                await Write_jiagong_BeiFang(dampResModel, dampResId, dampVals);
        //                break;

        //            case "PCT":
        //                Console.WriteLine($"找到表面张力检测的id了！是：{whiteTestIdsNames[i][0]}");
        //                var pctResult = await Call_Button_BeiFang("atm.plm.top.inspect", (int)whiteTestIdsNames[i][0]);
        //                int pctResId = (int)pctResult["result"]["res_id"];
        //                string pctResModel = (string)pctResult["result"]["res_model"];
        //                var pctVals = new Dictionary<string, object>
        //                {
        //                    {"pct_condition", readOrWrite.PctCondition},
        //                    {"pct_remark", readOrWrite.PctRemark},
        //                    {"pct_time", readOrWrite.PctTime},
        //                };
        //                await Write_jiagong_BeiFang(pctResModel, pctResId, pctVals);
        //                break;

        //            case "光泽度":
        //                Console.WriteLine($"找到光泽度检测的id了！是：{whiteTestIdsNames[i][0]}");
        //                var glossResult = await Call_Button_BeiFang("atm.plm.top.inspect", (int)whiteTestIdsNames[i][0]);
        //                int glossResId = (int)glossResult["result"]["res_id"];
        //                string glossResModel = (string)glossResult["result"]["res_model"];
        //                var glossVals = new Dictionary<string, object>
        //                {
        //                    {"value_max", readOrWrite.GlossValueMax},
        //                    {"value_min", readOrWrite.GlossValueMin},
        //                };
        //                await Write_jiagong_BeiFang(glossResModel, glossResId, glossVals);
        //                break;

        //            case "表面烘烤":
        //                Console.WriteLine($"找到光泽度检测的id了！是：{whiteTestIdsNames[i][0]}");
        //                var bakeMistResult = await Call_Button_BeiFang("atm.plm.top.inspect", (int)whiteTestIdsNames[i][0]);
        //                int bakeMistResId = (int)bakeMistResult["result"]["res_id"];
        //                string bakeMistResModel = (string)bakeMistResult["result"]["res_model"];
        //                var bakeMistVals = new Dictionary<string, object>
        //                {
        //                    {"bake_mist_time", readOrWrite.BakeMistTime},
        //                    {"bake_mist_remark", readOrWrite.BakeMistRemark},
        //                };
        //                await Write_jiagong_BeiFang(bakeMistResModel, bakeMistResId, bakeMistVals);
        //                break;

        //            case "失重":
        //                Console.WriteLine($"找到光泽度检测的id了！是：{whiteTestIdsNames[i][0]}");
        //                var lostResult = await Call_Button_BeiFang("atm.plm.top.inspect", (int)whiteTestIdsNames[i][0]);
        //                int lostResId = (int)lostResult["result"]["res_id"];
        //                string lostResModel = (string)lostResult["result"]["res_model"];
        //                var lostVals = new Dictionary<string, object>
        //                {
        //                    {"lost_condition", readOrWrite.LostCondition},
        //                    {"lost_time", readOrWrite.LostTime},
        //                    {"lost_standard_val", readOrWrite.LostStandardVal},
        //                    {"lost_remark", readOrWrite.LostRemark},
        //                };
        //                await Write_jiagong_BeiFang(lostResModel, lostResId, lostVals);
        //                break;

        //            case "丙酮擦拭":
        //                Console.WriteLine($"找到光泽度检测的id了！是：{whiteTestIdsNames[i][0]}");
        //                var aceToneWipeResult = await Call_Button_BeiFang("atm.plm.top.inspect", (int)whiteTestIdsNames[i][0]);
        //                int aceToneWipeResId = (int)aceToneWipeResult["result"]["res_id"];
        //                string aceToneWipeResModel = (string)aceToneWipeResult["result"]["res_model"];
        //                var aceToneWipeVals = new Dictionary<string, object>
        //                {
        //                    {"acetone_wipe_remark", readOrWrite.AceToneWipeRemark},
        //                };
        //                await Write_jiagong_BeiFang(aceToneWipeResModel, aceToneWipeResId, aceToneWipeVals);
        //                break;

        //            case "百格":
        //                Console.WriteLine($"找到光泽度检测的id了！是：{whiteTestIdsNames[i][0]}");
        //                var crossCutResult = await Call_Button_BeiFang("atm.plm.top.inspect", (int)whiteTestIdsNames[i][0]);
        //                int crossCutResId = (int)crossCutResult["result"]["res_id"];
        //                string crossCutResModel = (string)crossCutResult["result"]["res_model"];
        //                var crossCutVals = new Dictionary<string, object>
        //                {
        //                    {"cross_cut_remark", readOrWrite.CrossCutRemark},
        //                };
        //                await Write_jiagong_BeiFang(crossCutResModel, crossCutResId, crossCutVals);
        //                break;

        //            case "剪切力":
        //                Console.WriteLine($"找到剪切力检测的id了！是：{whiteTestIdsNames[i][0]}");
        //                var shearForceResult = await Call_Button_BeiFang("atm.plm.top.inspect", (int)whiteTestIdsNames[i][0]);
        //                int shearForceResId = (int)shearForceResult["result"]["res_id"];
        //                string shearForceResModel = (string)shearForceResult["result"]["res_model"];
        //                var shearForceVals = new Dictionary<string, object>
        //                {
        //                    {"shear_force_remark", readOrWrite.ShearForceRemark},
        //                    {"shear_force_min", readOrWrite.ShearForceMin},
        //                    {"shear_force_max", readOrWrite.ShearForceMax},
        //                };
        //                await Write_jiagong_BeiFang(shearForceResModel, shearForceResId, shearForceVals);
        //                break;

        //            case "尺寸录入":
        //            case "外观检测":
        //            case "简单外观检测":
        //                Console.WriteLine($"找到3类默认白片检测的id了！是：{whiteTestIdsNames[i][0]}");
        //                var param1 = new List<object>();
        //                param1.Add(db_beifang);
        //                if (uid == null || uid == 0)
        //                    uid = await GetOdooUid_BeiFang(userName_beifang, password_beifang);
        //                param1.Add(uid);
        //                param1.Add(password_beifang);
        //                param1.Add("atm.plm.top");
        //                param1.Add("write");  //web_save  write都可以修改参数，write不需要传入specification参数
        //                var vals3 = new Dictionary<string, object>
        //                {
        //                     { "white_test_ids", new List<object>  //修改白片检测项目
        //                                    {
        //                                        new List<object> //镀层厚度检测
        //                                        {
        //                                            1,
        //                                            (int)whiteTestIdsNames[i][0],
        //                                            new Dictionary<string, object>
        //                                            {
        //                                                {"qc_level", readOrWrite.WhiteInspectSizeInputQCLevel}, // 检测类型
        //                                                {"sample_qty", readOrWrite.WhiteInspectSizeInputSampleQty}, // 送检数量
        //                                            }

        //                                        },
        //                                    }

        //                     },
        //                };
        //                param1.Add(new List<object> { (int)id["id"], vals3 });
        //                data = await Call_BeiFang("object", "execute_kw", param1);
        //                break;

        //            default:
        //                Console.WriteLine($"无需编辑检测类型：{whiteTestIdsNames[i][1]}");
        //                break;
        //        }
        //    }
        //    Console.WriteLine(data);

        //    return new
        //    {
        //        rows = r,
        //        total = r.Count
        //    };
        //}
        public async Task<JObject> Write_jiagong_BeiFang(string model, int id, Dictionary<string, object> info)
        {
            Console.WriteLine("wwwwww");
            var param = new List<object>();
            param.Add(db_beifang);
            if (uid == null || uid == 0)
                uid = await GetOdooUid_BeiFang(userName_beifang, password_beifang);
            param.Add(uid);
            param.Add(password_beifang);
            param.Add(model);
            param.Add("write");  //method
            string[] modelArray = { "atm.qc.inspect.bh.spec", "atm.qc.inspect.thickness.spec", "atm.qc.inspect.salt.spec" };
            //if (modelArray.Contains(model))
            //{
            //    param.Add(new List<object> { new List<object> { id }, info });  //正式要添加的参数
            //}
            //else
            //{
            //    param.Add(new List<object> { id, info });  //正式要添加的参数
            //}
            param.Add(new List<object> { new List<object> { id }, info });  //正式要添加的参数

            var vals2 = new Dictionary<string, object>
            {
                { "specification", new Dictionary<string, object>() },
            };
            //param.Add(vals2);
            JObject data = null;
            try
            {
                data = await Call_BeiFang("object", "execute_kw", param);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"获取aMES数据失败，请求内容：{JsonConvert.SerializeObject(param)}，错误信息：{ex.Message}");
                throw new AppException(ex.ToString());
            }
            Console.WriteLine(data);
            return data;
        }

        /// <summary>
        /// 点击“工艺”按钮后，返回的值，res_id  res_model这两个值对于接下来修改页卡中的信息有用
        /// </summary>
        /// <param name="model">查找的模型</param>
        /// <param name="id">查找的id</param>
        /// <returns></returns>
        /// <exception cref="AppException"></exception>
        public async Task<JObject> Call_Button_BeiFang(string model, int id)
        {
            Console.WriteLine("wwwwww");
            var param = new List<object>();
            param.Add(db_beifang);
            if (uid == null || uid == 0)
                uid = await GetOdooUid_BeiFang(userName_beifang, password_beifang);
            param.Add(uid);
            param.Add(password_beifang);
            param.Add(model);
            if(model == "atm.plm.top.inspect")
            {
                param.Add("spec_details");  //method
            }
            else
            {
                param.Add("technology_details");  //method
            }

            param.Add(  new List<object> { new List<int> { id }  });

            // 创建最终结果
            var result = new Dictionary<string, object>
            {
                //{ "action", new Dictionary<string, object>() },
                { "res_id", new Dictionary<string, object>() },
                //{ "res_model", new Dictionary<string, object>() }
            };

            //param.Add(result);  //有的接口不需要写返回值，加了这个就会报错
            JObject data = null;
            try
            {
                data = await Call_BeiFang("object", "execute_kw", param);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"获取aMES数据失败，请求内容：{JsonConvert.SerializeObject(param)}，错误信息：{ex.Message}");
                throw new AppException(ex.ToString());
            }
            Console.WriteLine(data);
            return data;
        }

        public async Task<object> CallWrite_Shape_BeiFang(Dictionary<object, object> readOrWrite, string type)
        {
            var param = new List<object>();

            param.Add(db_beifang);
            //获取维度对应的ID，再通过ID改尺寸
            if (uid == null || uid == 0)
                uid = await GetOdooUid_BeiFang(userName_beifang, password_beifang);
            param.Add(uid);
            param.Add(password_beifang);
            param.Add("atm.plm.shape");//修改产品工艺单中的毛坯尺寸内容模型
            param.Add("web_save");
            if (type == "毛坯尺寸")  //修改毛坯尺寸
            {
                List<int> dimenIds = (List<int>)await SyncRoughShapeDimenIds_BF((long)readOrWrite["RoughShapeId"]);
                object vals3;
                if (dimenIds.Count == 3)
                {
                    vals3 = new Dictionary<string, object>  //测试语句，只修改特定内容
                        {
                              { "magnetic_angle", readOrWrite["MagneticAngle"] },  //修改毛坯尺寸中的磁方向角度（测试成功）
                              { "dimens", new List<object>  //修改尺寸
                                    {
                                        new List<object> { 1, dimenIds[0], new Dictionary<string, object> { { "dimen", readOrWrite["DimenSize1"] }, { "tol", readOrWrite["DimenTol1"] } } },
                                        new List<object> { 1, dimenIds[1], new Dictionary<string, object> { { "dimen", readOrWrite["DimenSize2"] }, { "tol", readOrWrite["DimenTol2"] } } },
                                        new List<object> { 1, dimenIds[2], new Dictionary<string, object> { { "dimen", readOrWrite["DimenSize3"] }, { "tol", readOrWrite["DimenTol3"] } } }
                                    }
                               }

                        };
                }
                else
                {
                    vals3 = new Dictionary<string, object>
                        {
                              { "magnetic_angle", readOrWrite["MagneticAngle"] },  //修改毛坯尺寸中的磁方向角度（测试成功）
                              { "dimens", new List<object>  //修改尺寸
                                    {
                                        new List<object> { 1, dimenIds[0], new Dictionary<string, object> { { "dimen", readOrWrite["DimenSize1"] }, { "tol", readOrWrite["DimenTol1"] } } },
                                        new List<object> { 1, dimenIds[1], new Dictionary<string, object> { { "dimen", readOrWrite["DimenSize2"] }, { "tol", readOrWrite["DimenTol2"] } } },
                                     }
                               }

                        };
                }

                //param.Add(new List<object> { (int)id["id"], vals3 });  //正式要添加的参数
                param.Add(new List<object> { (long)readOrWrite["RoughShapeId"], vals3 });
            }
            else  // 修改产品尺寸
            {
                List<int> dimenIds = (List<int>)await SyncRoughShapeDimenIds_BF((long)readOrWrite["ProductShapeId"]);
                object vals3;
                if (dimenIds.Count == 3)
                {
                    vals3 = new Dictionary<string, object>  
                        {
                              { "dimens", new List<object>  //修改尺寸
                                    {
                                        new List<object> { 1, dimenIds[0], new Dictionary<string, object> { { "dimen", readOrWrite["ChanpinProductDimesSize1"] }, { "tol", readOrWrite["ChanpinProductTol1"] } } },
                                        new List<object> { 1, dimenIds[1], new Dictionary<string, object> { { "dimen", readOrWrite["ChanpinProductDimesSize2"] }, { "tol", readOrWrite["ChanpinProductTol2"] } } },
                                        new List<object> { 1, dimenIds[2], new Dictionary<string, object> { { "dimen", readOrWrite["ChanpinProductDimesSize3"] }, { "tol", readOrWrite["ChanpinProductTol3"] } } }
                                    }
                               }

                        };
                }
                else
                {
                    vals3 = new Dictionary<string, object>
                        {
                              { "dimens", new List<object>  //修改尺寸
                                    {
                                        new List<object> { 1, dimenIds[0], new Dictionary<string, object> { { "dimen", readOrWrite["ChanpinProductDimesSize1"] }, { "tol", readOrWrite["ChanpinProductTol1"] } } },
                                        new List<object> { 1, dimenIds[1], new Dictionary<string, object> { { "dimen", readOrWrite["ChanpinProductDimesSize2"] }, { "tol", readOrWrite["ChanpinProductTol2"] } } },
                                    }
                               }

                        };
                }

                param.Add(new List<object> { (long)readOrWrite["ProductShapeId"], vals3 });
            }
            var vals2 = new Dictionary<string, object>
            {
                { "specification", new Dictionary<string, object>() },
            };
            param.Add(vals2);
            JObject data = null;
            try
            {
                data = await Call_BeiFang("object", "execute_kw", param);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"获取aMES数据失败，请求内容：{JsonConvert.SerializeObject(param)}，错误信息：{ex.Message}");
                throw new AppException(ex.ToString());
            }
            var r = new List<object>();

            Console.WriteLine(data);
            return new
            {
                rows = r,
                total = r.Count
            };
        }

        public async Task<JObject> CallNameGet(string model, List<object> domain,  object pageData)
        {
            var param = new List<object>();
            param.Add(db);
            //if (uid == null || uid == 0)
            uid = await GetOdooUid(userName, password);
            param.Add(uid);
            param.Add(password);
            param.Add(model);
            param.Add("name_get");
            param.Add(pageData);
            JObject data = null;
            try
            {
                data = await Call("object", "execute_kw", param);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"获取aMES数据失败，请求内容：{JsonConvert.SerializeObject(param)}，错误信息：{ex.Message}");
                throw new AppException(ex.ToString());
            }
            return data;
        }

        public async Task<JObject> CallSearchRead(string model, List<object> domain, List<string> fields, object pageData)
        {
            var param = new List<object>();
            param.Add(db);
            // if (uid == null || uid == 0)
                uid = await GetOdooUid(userName, password);
            param.Add(uid);
            param.Add(password);
            param.Add(model);
            param.Add("search_read");
            param.Add(new List<object> { domain, fields });
            param.Add(pageData);
            JObject data = null;
            try
            {
                data = await Call("object", "execute_kw", param);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"获取aMES数据失败，请求内容：{JsonConvert.SerializeObject(param)}，错误信息：{ex.Message}");
                throw new AppException(ex.ToString());
            }
            
            return data;
        }

        public async Task<JObject> CallSearchRead_Kg_Device(string model, List<object> domain, List<string> fields, object pageData)
        {
            var param = new List<object>();
            param.Add(db_kg_device);
            // if (uid == null || uid == 0)
            uid = await GetOdooUid_Kg_Device(userName_kg_device, password_kg_device);
            param.Add(uid);
            param.Add(password_kg_device);
            param.Add(model);
            param.Add("search_read");
            param.Add(new List<object> { domain, fields });
            param.Add(pageData);
            JObject data = null;
            try
            {
                data = await Call_Kg_Device("object", "execute_kw", param);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"获取aMES数据失败，请求内容：{JsonConvert.SerializeObject(param)}，错误信息：{ex.Message}");
                throw new AppException(ex.ToString());
            }

            return data;
        }
        public async Task<JObject> CallSearchReadBH(string model, List<object> domain, List<string> fields, object pageData)
        {
            var param = new List<object>();
            param.Add(db);
            if (uid == null || uid == 0)
                uid = await GetOdooUid(userName, password);
            param.Add(uid);
            param.Add(password);
            param.Add(model);
            param.Add("search_read");
            param.Add(new List<object> { domain, fields });
            param.Add(pageData);
            JObject data = null;
            try
            {
                data = await Call("object", "execute_kw", param);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"获取aMES数据失败，请求内容：{JsonConvert.SerializeObject(param)}，错误信息：{ex.Message}");
                throw new AppException(ex.ToString());
            }
            // 在异步方法中使用
            //async Task MyMethod()
            //{
            //    Console.WriteLine("开始延时");
            //    await Task.Delay(1000); // 异步等待 1 秒
            //    Console.WriteLine("延时结束");
            //}

            // 调用
            //await MyMethod();

            return data;
        }

        public async Task<JObject> CallSearchRead_AiKe(string model, List<object> domain, List<string> fields, object pageData)
        {
            var param = new List<object>();
            param.Add(db_aike);
            //if (uid == null || uid == 0)
            uid = await GetOdooUid_AiKe(userName_aike, password_aike);
            param.Add(uid);
            param.Add(password_aike);
            param.Add(model);
            param.Add("search_read");
            param.Add(new List<object> { domain, fields });
            param.Add(pageData);
            JObject data = null;
            try
            {
                data = await Call_AiKe("object", "execute_kw", param);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"获取aMES数据失败，请求内容：{JsonConvert.SerializeObject(param)}，错误信息：{ex.Message}");
                throw new AppException(ex.ToString());
            }
            return data;
        }

        public async Task<JObject> CallSearchReadBH_AiKe(string model, List<object> domain, List<string> fields, object pageData)
        {
            var param = new List<object>();
            param.Add(db_aike);
            if (uid == null || uid == 0)
                uid = await GetOdooUid_AiKe(userName_aike, password_aike);
            param.Add(uid);
            param.Add(password_aike);
            param.Add(model);
            param.Add("search_read");
            param.Add(new List<object> { domain, fields });
            param.Add(pageData);
            JObject data = null;
            try
            {
                data = await Call_AiKe("object", "execute_kw", param);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"获取aMES数据失败，请求内容：{JsonConvert.SerializeObject(param)}，错误信息：{ex.Message}");
                throw new AppException(ex.ToString());
            }
            //// 在异步方法中使用
            //async Task MyMethod()
            //{
            //    Console.WriteLine("开始延时");
            //    await Task.Delay(1000); // 异步等待 1 秒
            //    Console.WriteLine("延时结束");
            //}

            //// 调用
            //await MyMethod();
            return data;
        }

        public async Task<JObject> CallSearchRead_BeiFang(string model, List<object> domain, List<string> fields, object pageData)
        {
            var param = new List<object>();
            param.Add(db_beifang);
            //if (uid == null || uid == 0)
            Console.WriteLine("ceshi", userName_beifang, password_beifang);
            uid = await GetOdooUid_BeiFang(userName_beifang, password_beifang);
            param.Add(uid);
            param.Add(password_beifang);
            param.Add(model);
            param.Add("search_read");
            //param.Add("web_search_read");
            //var productUomFields = new Dictionary<string, object>
            // {
            //     //{ "id", new Dictionary<string, object>() },
            //     { "fields", new Dictionary<string, object>
            //         {
            //             {
            //                 "display_name", new Dictionary<string, object>()
            //             }
            //         }
            //     }


            // };
            //// 创建specification结构
            //var specification = new Dictionary<string, object>
            //{
            //    { "quantity", new Dictionary<string, object>() },
            //    { "product_id", productUomFields }
            //};
            //var result = new Dictionary<string, object>
            //    {
            //         { "specification", specification },
            //    };
            //param.Add(new List<object> { domain });
            //param.Add(result);

            param.Add(new List<object> { domain, fields });
            param.Add(pageData);

            JObject data = null;
            try
            {
                data = await Call_BeiFang("object", "execute_kw", param);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"获取aMES数据失败，请求内容：{JsonConvert.SerializeObject(param)}，错误信息：{ex.Message}");
                throw new AppException(ex.ToString());
            }
            return data;
        }

        public async Task<JObject> CallSearchReadBH_BeiFang(string model, List<object> domain, List<string> fields, object pageData)
        {
            var param = new List<object>();
            param.Add(db_beifang);
            if (uid == null || uid == 0)
                uid = await GetOdooUid_BeiFang(userName_beifang, password_beifang);
            param.Add(uid);
            param.Add(password_beifang);
            param.Add(model);
            param.Add("search_read");
            param.Add(new List<object> { domain, fields });
            param.Add(pageData);
            JObject data = null;
            try
            {
                data = await Call_BeiFang("object", "execute_kw", param);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"获取aMES数据失败，请求内容：{JsonConvert.SerializeObject(param)}，错误信息：{ex.Message}");
                throw new AppException(ex.ToString());
            }
            //// 在异步方法中使用
            //async Task MyMethod()
            //{
            //    Console.WriteLine("开始延时");
            //    await Task.Delay(1000); // 异步等待 1 秒
            //    Console.WriteLine("延时结束");
            //}

            //// 调用
            //await MyMethod();
            return data;
        }
        //读取空港详细页面中的内容，read方法
        public async Task<JObject> CallRead(string model, List<object> domain, List<string> fields, object pageData)
        {
            var param = new List<object>();
            param.Add(db);
            //if (uid == null || uid == 0)
                uid = await GetOdooUid(userName, password);
            param.Add(uid);
            param.Add(password);
            param.Add(model);
            param.Add("read");
            param.Add(new List<object> { domain, fields });
            // param.Add(pageData);
            JObject data = null;
            try
            {
                data = await Call("object", "execute_kw", param);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"获取aMES数据失败，请求内容：{JsonConvert.SerializeObject(param)}，错误信息：{ex.Message}");
                throw new AppException(ex.ToString());
            }
            return data;
        }

        public async Task<JObject> CallRead_Kg_Device(string model, List<object> domain, List<string> fields, object pageData)
        {
            var param = new List<object>();
            param.Add(db);
            //if (uid == null || uid == 0)
            uid = await GetOdooUid(userName_kg_device, password_kg_device);
            param.Add(uid);
            param.Add(password_kg_device);
            param.Add(model);
            param.Add("read");
            param.Add(new List<object> { domain, fields });
            // param.Add(pageData);
            JObject data = null;
            try
            {
                data = await Call_Kg_Device("object", "execute_kw", param);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"获取aMES数据失败，请求内容：{JsonConvert.SerializeObject(param)}，错误信息：{ex.Message}");
                throw new AppException(ex.ToString());
            }
            return data;
        }
        //读取爱科详细页面中的内容，read方法
        public async Task<JObject> CallRead_AiKe(string model, List<object> domain, List<string> fields, object pageData)
        {
            var param = new List<object>();
            param.Add(db_aike);
            //if (uid == null || uid == 0)
                uid = await GetOdooUid_AiKe(userName_aike, password_aike);
            param.Add(uid);
            param.Add(password_aike);
            param.Add(model);
            param.Add("read");
            param.Add(new List<object> { domain, fields });
            // param.Add(pageData);
            JObject data = null;
            try
            {
                data = await Call_AiKe("object", "execute_kw", param);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"获取aMES数据失败，请求内容：{JsonConvert.SerializeObject(param)}，错误信息：{ex.Message}");
                throw new AppException(ex.ToString());
            }
            return data;
        }

        //读取北方详细页面中的内容，read方法
        public async Task<JObject> CallRead_BeiFang(string model, List<object> domain, List<string> fields, object pageData)
        {
            var param = new List<object>();
            param.Add(db_beifang);
            //if (uid == null || uid == 0)
            uid = await GetOdooUid_BeiFang(userName_beifang, password_beifang);
            param.Add(uid);
            param.Add(password_beifang);
            param.Add(model);
            if(model == "atm.qc.inspect.bh.spec")
            {
                // 创建order_line的fields结构
                var linesFields = new Dictionary<string, object>
                {
                      { "fields", new Dictionary<string, object>
                        {
                            { "id", new Dictionary<string, object>() },
                            { "name", new Dictionary<string, object>() }
                        }
                      }
                };

                // 创建specification结构
                var specification = new Dictionary<string, object>
                {
                     { "lines", linesFields }
                };

                // 创建最终结果
                var result = new Dictionary<string, object>
                {
                     { "specification", specification }
                };
                param.Add("web_read");
                param.Add(new List<object> { domain });
                param.Add(result);
            }
            else
            {
                param.Add("read");
                param.Add(new List<object> { domain, fields });
            }
            // param.Add(pageData);
            JObject data = null;
            try
            {
                data = await Call_BeiFang("object", "execute_kw", param);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"获取aMES数据失败，请求内容：{JsonConvert.SerializeObject(param)}，错误信息：{ex.Message}");
                throw new AppException(ex.ToString());
            }
            return data;
        }

        /// <summary>
        /// 获取odoo平台用户id
        /// </summary>
        //public async Task<int?> GetOdooUid(string username, string password)
        //{
        //    var res = await Call("common", "login", new List<dynamic> { db, username, password });
        //    return Convert.ToInt32(res["result"]);
        //}
        // 保留默认db的旧方法（兼容原有调用）
        public async Task<int?> GetOdooUid(string username, string password)
        {
            // 使用默认db（例如从配置中读取）
            return await GetOdooUid(db, username, password);
        }
        // 新增带db参数的重载方法（用于动态修改db）
        public async Task<int?> GetOdooUid(string db, string username, string password)
        {
            var res = await Call("common", "login", new List<dynamic> { db, username, password });
            return Convert.ToInt32(res["result"]);
        }
        public async Task<int?> GetOdooUid_Kg_Device(string username, string password)
        {
            var res = await Call_Kg_Device("common", "login", new List<dynamic> { db_kg_device, username, password });
            return Convert.ToInt32(res["result"]);
        }
        public async Task<int?> GetOdooUid_AiKe(string username, string password)
        {
            var res = await Call_AiKe("common", "login", new List<dynamic> { db_aike, username, password });
            return Convert.ToInt32(res["result"]);
        }

        public async Task<int?> GetOdooUid_BeiFang(string username, string password)
        {
            var res = await Call_BeiFang("common", "login", new List<dynamic> { db_beifang, username, password });
            return Convert.ToInt32(res["result"]);
        }

        /// <summary>
        /// 具体业务调用
        /// 如果报错则会再调用一次
        /// </summary>
        public async Task<JObject> BusinessCall(string service, string method, List<dynamic> args)
        {
            JObject data = null;
            try
            {
                //if (uid == null || uid == 0) 
                    uid = await GetOdooUid(userName, password);
                args[1] = uid;
                data = await Call(service, method, args);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"获取aMES数据失败，{service}，{method}，{JsonConvert.SerializeObject(args)}，信息：{ex.Message}");
                throw new AppException(ex.ToString());
            }
            return data;
        }

        /// <summary>
        /// 通过电镀生产任务号获取产出的小lot数据
        /// </summary>
        public async Task<List<dynamic>> GetPrdTaskLot(string taskNo)
        {
            var message = "";
            var qDomain = new List<object> {
                new List<object> { "production_type", "=", "white" },
                new List<object> { "name", "=", taskNo }
            };
            var qFields = new List<string> {
                "name",
                "state",
                "quality_judge",
                "move_created_ids",
                "move_created_ids2",
            };
            var qPage = new { context = new { lang = "zh_CN", tz = "Asia/Shanghai" }, limit = 10, offset = 0 };
            var resp = await CallSearchRead("mrp.production", qDomain, qFields, qPage);
            if (resp.ContainsKey("error"))
            {
                message = $"【拉取单据失败】{resp["error"].ToString()}";
                logger.LogError(message);
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];
            if (res == null || res.Count <= 0)
            {
                throw new AppException($"没有从mes获取到单据数据{taskNo}");
            }
            //move_created_ids2为未产出数量的id  move_created_ids为产出数量的id
            var moveIds = res[0]["move_created_ids2"] is JArray ? ((JArray)res[0]["move_created_ids2"]) : null;
            if (moveIds.Count == 0)
            {
                moveIds = res[0]["move_created_ids"] is JArray ? ((JArray)res[0]["move_created_ids"]) : null;

            }
            if (moveIds == null)
            {
                throw new AppException($"任务未获取到产出批次信息");
            }
            //else if (moveIds.Count <= 1)
            //{
            //    throw new AppException($"任务不是小批次管理或者还未产出");
            //}

            var qDomain2 = new List<object> {
                new List<object> { "id", "in", moveIds.Select(a => int.Parse(a.ToString())).ToArray()},
            };
            var qFields2 = new List<string> { "restrict_lot_id", "state", "product_id", "product_qty", "product_uom_qty", "product_uom", "planned_qty" };
            var qPage2 = new
            {
                context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
                limit = 999999,
                offset = 0,
                order = "",
            };
            var resp2 = await CallSearchRead("stock.move", qDomain2, qFields2, qPage2);
            if (resp2.ContainsKey("error"))
            {
                message = $"【拉取单据批次失败】{resp2["error"].ToString()}";
                logger.LogError(message);
                throw new AppException(message);
            }
            var resDetail = (JArray)resp2["result"];
            if (resDetail == null || resDetail.Count <= 0)
            {
                throw new AppException($"没有从mes获取到单据明细数据{taskNo}");
            }

            var lst = resDetail.Select(a => new
            {
                task_no = res[0]["name"].ToString(),
                lot_id = a["restrict_lot_id"] is JArray ? int.Parse(a["restrict_lot_id"][0].ToString()) : 0,
                lot_no = a["restrict_lot_id"] is JArray ? a["restrict_lot_id"][1].ToString() : "",
                state = a["state"].ToString(),
                product_id = a["product_id"] is JArray ? int.Parse(a["product_id"][0].ToString()) : 0,
                product_name = a["product_id"] is JArray ? a["product_id"][1].ToString() : "",
                product_uom_qty = Convert.ToDecimal(a["product_uom_qty"]),
                product_uom_name = a["product_uom"] is JArray ? a["product_uom"][1].ToString() : ""
            } as object).ToList();
            return lst;
        }

        /// <summary>
        /// 通过电镀生产任务号获取报工记录中的小lot数据
        /// </summary>
        public async Task<List<dynamic>> GetPrdTaskLot_register(string taskNo)
        {
            var message = "";
            var qDomain = new List<object> {
                new List<object> { "production_type", "=", "white" },
                new List<object> { "name", "=", taskNo }
            };
            var qFields = new List<string> {
                "name",
                "state",
                "quality_judge",
                "register_ids"
            };
            var qPage = new { context = new { lang = "zh_CN", tz = "Asia/Shanghai" }, limit = 10, offset = 0 };
            var resp = await CallSearchRead("mrp.production", qDomain, qFields, qPage);
            if (resp.ContainsKey("error"))
            {
                message = $"【拉取单据失败】{resp["error"].ToString()}";
                logger.LogError(message);
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];
            if (res == null || res.Count <= 0)
            {
                throw new AppException($"没有从mes获取到单据数据{taskNo}");
            }
            //move_created_ids2为未产出数量的id  move_created_ids为产出数量的id
            var register_ids = res[0]["register_ids"] is JArray ? ((JArray)res[0]["register_ids"]) : null;

            if (register_ids == null)
            {
                throw new AppException($"任务未获取到产出批次信息");
            }
            //else if (moveIds.Count <= 1)
            //{
            //    throw new AppException($"任务不是小批次管理或者还未产出");
            //}

            var qDomain2 = new List<object> {
                new List<object> { "id", "in", register_ids.Select(a => int.Parse(a.ToString())).ToArray()},
            };
            var qFields2 = new List<string> { "lot_id", "state", "product_id", "qty" };
            var qPage2 = new
            {
                context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
                limit = 999999,
                offset = 0,
                order = "",
            };
            var resp2 = await CallSearchRead("mrp.production.product.register", qDomain2, qFields2, qPage2);
            if (resp2.ContainsKey("error"))
            {
                message = $"【拉取单据批次失败】{resp2["error"].ToString()}";
                logger.LogError(message);
                throw new AppException(message);
            }
            var resDetail = (JArray)resp2["result"];
            if (resDetail == null || resDetail.Count <= 0)
            {
                throw new AppException($"没有从mes获取到单据明细数据{taskNo}");
            }

            var lst = resDetail.Select(a => new
            {
                task_no = res[0]["name"].ToString(),
                lot_id = a["lot_id"] is JArray ? int.Parse(a["lot_id"][0].ToString()) : 0,
                lot_no = a["lot_id"] is JArray ? a["lot_id"][1].ToString() : "",
                state = a["state"].ToString(),
                product_id = a["product_id"] is JArray ? int.Parse(a["product_id"][0].ToString()) : 0,
                product_name = a["product_id"] is JArray ? a["product_id"][1].ToString() : "",
                qty = Convert.ToDecimal(a["qty"]),
                //product_uom_name = a["product_uom"] is JArray ? a["product_uom"][1].ToString() : ""
            } as object).ToList();
            return lst;
        }

        /// <summary>
        /// 获取产品单重
        /// </summary>
        /// <param name="taskNo"></param>
        public async Task<object> SyncProductionUnitWeight(string name)
        {
            var qDomain = new List<object> {
                new List<object> { "name", "=", name }
            };

            var qFields = new List<string> {
                "id",
                "name",
                "weight_g",
            };
            var qPage = new
            {
                context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
                limit = 1,
                offset = 0,
            };

            var resp = await CallSearchRead("atm.plm.top", qDomain, qFields, qPage);
            if (resp.ContainsKey("error"))
            {
                var message = $"{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];
            if (res == null || res.Count <= 0)
            {
                return null;
            }
            return res[0];
        }
        public async Task<object> SyncProduction_BF(string name)
        {
            var qDomain = new List<object> {
                new List<object> { "name", "=", name }
            };

            var qFields = new List<string> {
                "id",
                "name",
            };
            var qPage = new
            {
                context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
                limit = 1,
                offset = 0,
            };

            var resp = await CallSearchRead_BeiFang("atm.plm.top", qDomain, qFields, qPage);
            if (resp.ContainsKey("error"))
            {
                var message = $"{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];
            if (res == null || res.Count <= 0)
            {
                return null;
            }
            return res[0];
        }

        public async Task<object> SyncRoughShapeDimenIds_BF(long roughshapeId)
        {
            Console.WriteLine("wwwwww");
            var param = new List<object>();
            param.Add(db_beifang);
            //if (uid == null || uid == 0)
            uid = await GetOdooUid_BeiFang(userName_beifang, password_beifang);
            param.Add(uid);
            param.Add(password_beifang);
            param.Add("atm.plm.shape");
            param.Add("web_read");
            param.Add(new List<object> { roughshapeId });
            var orderIdFields = new Dictionary<string, object>
             {
                 { "fields", new Dictionary<string, object>() }
             };

            var productUomFields = new Dictionary<string, object>
             {
                 //{ "id", new Dictionary<string, object>() },
                 { "fields", new Dictionary<string, object>
                     {
                         {
                             "display_name", new Dictionary<string, object>()
                         }
                     }
                 }


             };

            // 创建order_line的fields结构
            var dimensFields = new Dictionary<string, object>
             {
                 {"id", new Dictionary<string, object>() },

             };

            // 创建order_line结构
            var dimens = new Dictionary<string, object>
             {
                 { "fields", dimensFields }
             };

            // 创建specification结构
            var specification = new Dictionary<string, object>
             {
                 { "dimens", dimens }
             };

            // 创建最终结果
            var result = new Dictionary<string, object>
             {
                 { "specification", specification }
             };
            param.Add(result);
            JObject data = null;
            try
            {
                data = await Call_BeiFang("object", "execute_kw", param);
            }

            catch (Exception ex)
            {
                logger.LogError(ex, $"获取aMES数据失败，请求内容：{JsonConvert.SerializeObject(param)}，错误信息：{ex.Message}");
                throw new AppException(ex.ToString());
            }
            var res = (JArray)data["result"];
            var r = new List<int>();

            var x = (JObject)res[0];
            var x1 = x["dimens"];
            foreach ( var item in x1)
            {
                int id = item["id"].Value<int>();
                r.Add(id);
            }

            
            Console.WriteLine(data);
            return r;
        }
        public async Task<object> SyncProductionApplication_BeiFang()
        {
            var qDomain = new List<object>
            {
            };

            var qFields = new List<string> {
                "id",
                "name",
            };
            var qPage = new
            {
                context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
                limit = 80,
                offset = 0,
            };

            var resp = await CallSearchRead_BeiFang("atm.product.application", qDomain, qFields, qPage);
            if (resp.ContainsKey("error"))
            {
                var message = $"{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];
            if (res == null || res.Count <= 0)
            {
                return null;
            }
            var r = new List<object>();
            for (var i = 0; i < res.Count; i++)
            {
                var x = (JObject)res[i];
                r.Add(new
                {
                    ID = x["id"].ToString(),
                    Name = x["name"].ToString(),
                }) ;
            }
            return new
            {
                rows = r,
                total = res.Count
            };
        }

        public async Task<List<ResultAdd>> SyncProductInfo_BeiFang(string model)
        {
            var qDomain = new List<object>
            {
            };
            var qFields = model == "atm.plm.sheet.3_gongyi"
                ? new List<string> { "id", "code" }
                : new List<string> { "id", "name" };

            var qPage = new
            {
                context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
                limit = 1000000,
                offset = 0,
            };

            var resp = await CallSearchRead_BeiFang(model, qDomain, qFields, qPage);
            if (resp.ContainsKey("error"))
            {
                var message = $"{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];
            if (res == null || res.Count <= 0)
            {
                return null;
            }
            var r = new List<ResultAdd>();
            for (var i = 0; i < res.Count; i++)
            {
                var x = (JObject)res[i];
                r.Add(new ResultAdd
                {
                    Id = (int)x["id"],
                    Name = model == "atm.plm.sheet.3_gongyi" ? x["code"].ToString() : x["name"].ToString(),

                });
            }
            return r;
        }

        /// <summary>
        /// 获取产品客户代码
        /// </summary>
        /// <param name="taskNo"></param>
        public async Task<object> SyncProductionPartnerName(string name)
        {
            var qDomain = new List<object> {
                new List<object> { "name", "=", name }
            };

            var qFields = new List<string> {
                "id",
                "name",
                "partner_ids",
            };
            var qPage = new
            {
                limit = 1,
                offset = 0,
            };

            var resp = await CallSearchRead("atm.plm.top", qDomain, qFields, qPage);
            if (resp.ContainsKey("error"))
            {
                var message = $"{resp["error"].ToString()}";
                throw new AppException(message);
            }
            //获取客户代码的id数组
            var res = (JArray)resp["result"][0]["partner_ids"];

            //再通过id获取客户代码数组
            var r = new List<object>();
            for (var i = 0; i < res.Count; i++)
            {
                int partnerId = ((JValue)res[i]).Value<int>();
                String partnerName = await SyncProductionPartnerNamebyId(partnerId);
                r.Add(partnerName);
            }
            return r;
        }

        public async Task<object> SyncPartnerEmailInfo(string name)
        {
            var Data = await Db.Set<Email_Warn>().Where(x => x.PartnerId == name)
                .FirstAsync();
            return Data;
        }

        public async Task<String> SyncProductionPartnerNamebyId(int id)
        {
            var qDomain = new List<object> {
                new List<object> { "id", "=", id }
            };
            var qFields = new List<string> {
                "display_name"
            };

            var qPage = new
            {
                limit = 1,
                offset = 0,
            };
            //根据客户id获取对应的客户名称
            var resp = await CallSearchRead("res.partner", qDomain, qFields, qPage);
            if (resp.ContainsKey("error"))
            {
                var message = $"{resp["error"].ToString()}";
                throw new AppException(message);
            }
            //获取客户代码的id数组
            String partnerName = ((JValue)resp["result"][0]["display_name"]).ToString();
            return partnerName;
        }

        /// <summary>
        /// 获取报工ids
        /// </summary>
        /// <param name="id"></param>
        public async Task<object> GetRegisterIds(int id)
        {
            var qDomain = new List<object> {
                //new List<object> { "id", "=", id }
                id
            };

            var qFields = new List<string> {
                "register_ids"
            };
            var qPage = new
            {
                limit = 10000,
                offset = 0,
            };

            var resp = await CallRead("mrp.production", qDomain, qFields, qPage);
            if (resp.ContainsKey("error"))
            {
                var message = $"{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];

            if (res == null || res.Count <= 0)
            {
                return null;
            }
            return res[0];
        }
        /// <summary>
        /// CCD报工-通过电镀批次号获取各产出批次的各个信息
        /// </summary>
        /// 
        public async Task<object> SyncProductionTask_CCD(string taskNo = "")
        {
            if (taskNo?.Length < 7 | taskNo == null) {
                return new
                {
                    rows = new List<string>(),
                    total = 0
                };
            }
            string taskNo2 = taskNo;  //保存切分之前的电镀号
            if (taskNo.Contains("-"))
            {
                taskNo = taskNo.Split('-')[0]; // 取 "-" 前面的部分
            }

            var isSingle = taskNo.IsValuable();

            //同步的任务工序
            var typeArray = new[] { "white" };

            var qDomain = new List<object> {

                new List<object> { "production_type", "in", typeArray }
            };

            if (isSingle)
            {
                qDomain.Add(new List<object> { "name", "=", taskNo });
            }
            else
            {
                return new
                {
                    rows = new List<object> { },
                    total = 0
                };
            }

            //var check = await Db.Set<Ccd_Report>().Where(x => x.DianduNo == taskNo).AnyAsync();
            //if (check)
            //    throw new AppException($"{taskNo}数据已存在！");

            var qFields = new List<string> {
                "grade",
                "prodcut_spec",
                "raw_resume_weight",
                "state",
                "schedule_id",
                "product_id",
                "partner_id",
                "name",
                "raw_lot_id",
                "date_planned",
                "product_qty",
                "produced_qty",
                "production_type",
                "routing_id",
                "id"
            };
            var qPage = new
            {
                context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
                limit = 10,
                offset = 0,
                order = "name desc",
            };

            var resp = await CallSearchRead("mrp.production", qDomain, qFields, qPage);
            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];
            if (res == null || res.Count <= 0)
            {
                return null;
            }
            var r = new List<object>();
            var Product = "";

            for (var i = 0; i < res.Count; i++)
            {
                var x = (JObject)res[i];
                var productId = x["product_id"] is JArray ? JArray.FromObject(x["product_id"])[1].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "";
                //通过另一个接口，传入产品代码，获取该产品的单重，g
                var weight = (JObject)await SyncProductionUnitWeight(productId);
                var id = (int)x["id"];
                //通过另一个接口，传入电镀号，获取报工记录中的带小lot的所有id
                var ids = (JObject)await GetRegisterIds(id);
                //通过另一个接口，传入电镀号，获取报工记录中的带小lot的所有信息，data
                var data = await GetPrdTaskLot_register(x["name"].ToString());
                //如果传入的是带有小lot号的，则只返回一条对应的信息
                if (taskNo2.Contains("-"))
                {
                    for (int k = 0; k < data.Count; k++)
                    {
                        if (data[k].lot_no == taskNo2)
                        {
                            r.Add( new
                            {
                                DianduNo = data[k].lot_no,
                                ProductId = productId,
                                // ProductId = x["grade"] is JArray ? JArray.FromObject(x["grade"])[1].ToString() : "",
                                Grade = x["grade"] is JArray ? JArray.FromObject(x["grade"])[1].ToString() : "",
                                Spec = x["prodcut_spec"].ToString(),
                                IncomeQty = data[k].qty,
                                IncomeWeight = weight == null ? 0 : Math.Round((decimal)weight["weight_g"] * (int)data[k].qty / 1000, 2)
                            } );
                        }
                    }
                }
                else { 
                    r.AddRange(data.Select(j => new
                    {
                        DianduNo = j.lot_no,
                        ProductId = productId,
                        // ProductId = x["grade"] is JArray ? JArray.FromObject(x["grade"])[1].ToString() : "",
                        Grade = x["grade"] is JArray ? JArray.FromObject(x["grade"])[1].ToString() : "",
                        Spec = x["prodcut_spec"].ToString(),
                        IncomeQty = j.qty,
                        IncomeWeight = weight == null ? 0 : Math.Round((decimal)weight["weight_g"] * (int)j.qty / 1000, 2)
                    } as object).ToList());
                }
            }
            return new
            {
                rows = r,
                total = res.Count
            };
        }
        /// <summary>
        /// CCD报工-通过电镀批次号获取在检分中的信息
        /// </summary>
        /// 
        public async Task<object> SyncProductionTask_CCD_JF(string taskNo = "")
        {
            if (taskNo.Length < 7)
            {
                return new
                {
                    rows = new List<string>(),
                    total = 0
                };
            }
            
            var isSingle = taskNo.IsValuable();

            //同步的任务工序
            var typeArray = new[] { "final" };

            var qDomain = new List<object> {

                new List<object> { "production_type", "in", typeArray }
            };

            if (isSingle)
            {
                //这些条件是且的关系，需要注意
                //qDomain.Add(new List<object> { "state", "!=", "draft" });
                //qDomain.Add(new List<object> { "state", "!=", "cancel" });
                //qDomain.Add(new List<object> { "state", "!=", "confirmed" });
                //qDomain.Add(new List<object> { "state", "!=", "ready" });
                //qDomain.Add(new List<object> { "state", "!=", "done" });
                qDomain.Add(new List<object> { "raw_lot_id", "ilike", taskNo });
            }
            else
            {
                return new
                {
                    rows = new List<object> { },
                    total = 0
                };
            }

            //var check = await Db.Set<Ccd_Report>().Where(x => x.DianduNo == taskNo).AnyAsync();
            //if (check)
            //    throw new AppException($"{taskNo}数据已存在！");

            var qFields = new List<string> {
                "grade",
                "prodcut_spec",
                "raw_resume_weight",
                "state",
                "schedule_id",
                "product_id",
                "partner_id",
                "name",
                "raw_lot_id",
                "date_planned",
                "product_qty",
                "produced_qty",
                "production_type",
                "routing_id",
                "id"
            };
            var qPage = new
            {
                limit = 10000,
                offset = 0,
                order = "name desc",
            };

            var resp = await CallSearchRead("mrp.production", qDomain, qFields, qPage);
            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];
            if (res == null || res.Count <= 0)
            {
                return null;
            }
            var r = new List<object>();
            var Product = "";

            for (var i = 0; i < res.Count; i++)
            {
                var x = (JObject)res[i];
                var productId = x["product_id"] is JArray ? JArray.FromObject(x["product_id"])[1].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "";
                //通过另一个接口，传入产品代码，获取该产品的单重，g
                var weight = (JObject)await SyncProductionUnitWeight(productId);
                //var id = (int)x["id"];
                //通过另一个接口，传入电镀号，获取报工记录中的带小lot的所有id
                //var ids = (JObject)await GetRegisterIds(id);
                //通过另一个接口，传入电镀号，获取报工记录中的带小lot的所有信息，data
                //var data = await GetPrdTaskLot_register(x["name"].ToString());

                r.AddRange(res.Select(j => new
                {
                    DianduNo = taskNo,
                    ProductId = productId,
                    // ProductId = x["grade"] is JArray ? JArray.FromObject(x["grade"])[1].ToString() : "",
                    Grade = x["grade"] is JArray ? JArray.FromObject(x["grade"])[1].ToString() : "",
                    Spec = x["prodcut_spec"].ToString(),
                    IncomeQty = x["product_qty"],
                    IncomeWeight = weight == null ? 0 : Math.Round((decimal)weight["weight_g"] * (int)x["product_qty"] / 1000, 2)
                } as object).ToList());

            }
            return new
            {
                rows = r,
                total = res.Count
            };
        }
        public async Task<object> SyncProductionTask_wgjy(string taskNo = "")
        {
            var isSingle = taskNo.IsValuable();
            Console.WriteLine(taskNo);
            var typeArray = new[] { "final" };

            var qDomain = new List<object> {

                new List<object> { "production_type", "=", "final" }
            };

            if (isSingle)
            {
                Console.WriteLine("DDDDDD");
                qDomain.Add("|");
                qDomain.Add(new List<object> { "name", "ilike", taskNo });
                qDomain.Add(new List<object> { "origin", "ilike", taskNo });
                //Console.WriteLine(qDomain.ToArrayString);
            }
            //else
            //{
            //    qDomain.Add(new List<object> { "state", "=", "in_production" });
            //}

            var qFields = new List<string> {
                "id",
                "raw_lot_id",
                "product_id",
                "prodcut_spec",
                "grade",
                "raw_resume_stock_qty",
                "partner_id"
            };
            var qPage = new
            {
                limit = 10000,
                offset = 0,
                order = "name desc",
            };

            var resp = await Get_stoke_("mrp.production", qDomain, qFields, qPage);
            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];
            if (res == null || res.Count <= 0)
            {
                return null;
            }
            var Product = "";
            //Console.WriteLine(r);
            Console.WriteLine("FFF");
            object id_ = res[0]["id"];
            object partner = res[0]["partner_id"][1];
            object prodcut_spec = res[0]["prodcut_spec"];
            string raw_lot_id_ = (string)res[0]["raw_lot_id"][1];
            object grade = res[0]["grade"][1];
            object raw_resume_stock_qty = res[0]["raw_resume_stock_qty"];
            string raw_lot_id = "";
            if (raw_lot_id_.Contains("-C"))
            {
                Console.WriteLine("包含有");
                string aw_lot_id__ = raw_lot_id_.Split("-C")[0];
                raw_lot_id = aw_lot_id__;
            }
            else
            {
                Console.WriteLine("meiyou");
                raw_lot_id = raw_lot_id_;
            }
            Console.WriteLine(raw_lot_id);
            //var typeArray_1 = new[] { "final" };

            var qDomain_read = new List<object> {

                id_
            };

            var qFields_read = new List<string> {
                "id",
                "top_id",
                "lot_ids"
            };
            var qPage_read = new
            {
                limit = 10000,
                offset = 0,
                order = "name desc",
            };
            var resp_read = await Get_stoke_read("mrp.production", qDomain_read, qFields_read, qPage_read);
            var res_read = (JArray)resp_read["result"];
            string product_ = (string)res_read[0]["top_id"][1];
            object lot_ids = res_read[0]["lot_ids"][0];
            string product = "";
            if (raw_lot_id_.Contains(" "))
            {
                Console.WriteLine("包含有");
                product = product_.Replace(" ", "");
            }
            else
            {
                Console.WriteLine("meiyou");
                product = product_;
            }
            //var typeArray = new[] { "final" };

            var qDomain_3 = new List<object> {

                new List<object> { "lot_id", "ilike", raw_lot_id }
            };
            //else
            //{
            //    qDomain.Add(new List<object> { "state", "=", "in_production" });
            //}

            var qFields_3 = new List<string> {
                "id"
            };
            var qPage_3 = new
            {
                limit = 10000,
                offset = 0,
                order = "name desc",
            };
            var resp_3 = await Get_stoke_("atm.qc.inspect.visual", qDomain_3, qFields_3, qPage_3);
            Console.WriteLine(resp_3);
            var res_read_3 = (JArray)resp_3["result"];
            object id_4 = res_read_3[0]["id"];
            var qDomain_read_4 = new List<object> {
                id_4
            };

            var qFields_read_4 = new List<string> {
                "plating_qualified_fianl_qty",
                "sampling_reliability_qty"
            };
            var qPage_read_4 = new
            {
                limit = 10000,
                offset = 0,
                order = "name desc",
            };
            var resp_read_4 = await Get_stoke_read("atm.qc.inspect.visual", qDomain_read_4, qFields_read_4, qPage_read_4);
            var res_read_4 = (JArray)resp_read_4["result"];
            //object id_4 = res_read_4[0]["id"];
            object sampling_reliability_qty = res_read_4[0]["sampling_reliability_qty"];
            object plating_qualified_fianl_qty = res_read_4[0]["plating_qualified_fianl_qty"];

            var qDomain_read_5 = new List<object> {
                lot_ids
            };

            var qFields_read_5 = new List<string> {
                "id",
                "piece_weight"
            };
            var qPage_read_5 = new
            {
                limit = 10000,
                offset = 0,
                order = "name desc",
            };
            var resp_read_5 = await Get_stoke_read("stock.production.lot", qDomain_read_5, qFields_read_5, qPage_read_5);
            var res_read_5 = (JArray)resp_read_5["result"];
            object piece_weight = res_read_5[0]["piece_weight"];

            var qDomain_6 = new List<object> {

                new List<object> { "name", "ilike", product }
            };
            //else
            //{
            //    qDomain.Add(new List<object> { "state", "=", "in_production" });
            //}

            var qFields_6 = new List<string> {
                "id"
            };
            var qPage_6 = new
            {
                limit = 10000,
                offset = 0,
                order = "name desc",
            };
            var resp_6 = await Get_stoke_("atm.plm.top", qDomain_6, qFields_6, qPage_6);
            Console.WriteLine(resp_6);
            var res_read_6 = (JArray)resp_6["result"];
            object id_6 = res_read_6[0]["id"];

            var qDomain_read_7 = new List<object> {
                id_6
            };

            var qFields_read_7 = new List<string> {
                "id",
                "steelgrade_id"
            };
            var qPage_read_7 = new
            {
                limit = 10000,
                offset = 0,
                order = "name desc",
            };
            var resp_read_7 = await Get_stoke_read("atm.plm.top", qDomain_read_7, qFields_read_7, qPage_read_7);
            var res_read_7 = (JArray)resp_read_7["result"];
            object steelgrade_id = res_read_7[0]["steelgrade_id"];
            Console.WriteLine(steelgrade_id.GetType());
            string recycle_grade = "";
            if (steelgrade_id.GetType() == typeof(bool))
            {
                recycle_grade = "";
            }
            else
            {
                object steelgrade_id_ = res_read_7[0]["steelgrade_id"][0];
                var qDomain_read_8 = new List<object> {
                steelgrade_id_
                };

                var qFields_read_8 = new List<string> {
                "id",
                "recycle_grade"
                };
                var qPage_read_8 = new
                {
                    limit = 10000,
                    offset = 0,
                    order = "name desc",
                };
                var resp_read_8 = await Get_stoke_read("atm.product.steelgrade", qDomain_read_8, qFields_read_8, qPage_read_8);
                var res_read_8 = (JArray)resp_read_8["result"];
                recycle_grade = (string)res_read_8[0]["recycle_grade"];
            }
            var r = new List<object>();
            r.Add(new
            {
                product = product,
                partner = partner,
                prodcut_spec = prodcut_spec,
                raw_lot_id = raw_lot_id,
                raw_resume_stock_qty = raw_resume_stock_qty,
                piece_weight = piece_weight,
                recycle_grade = recycle_grade,
                grade = grade,
                plating_qualified_fianl_qty = plating_qualified_fianl_qty,
                sampling_reliability_qty = sampling_reliability_qty,
            });
            //for (var i = 0; i < res.Count; i++)
            //{
            //    var x = (JObject)res[i];
            //    Console.WriteLine(x);
            //    Console.WriteLine(i);
            //r.Add(new
            //{               

            //});
            //    DianduNo = x["name"].ToString(),
            //    ProductId = x["product_id"] is JArray ? JArray.FromObject(x["product_id"])[1].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
            //    Grade = x["grade"] is JArray ? JArray.FromObject(x["grade"])[1].ToString() : "",
            //    Spec = x["prodcut_spec"].ToString(),
            //    IncomeQty = (int)x["produced_qty"],
            //});
            //}
            return new
            {
                rows = r,
                total = res.Count
            };
        }
        public async Task<JObject> Get_stoke_read(string model, List<object> domain, List<string> fields, object pageData)
        {
            Console.WriteLine("wwwwww");
            var param = new List<object>();
            param.Add(db);
            //if (uid == null || uid == 0)
                uid = await GetOdooUid(userName, password);
            param.Add(uid);
            param.Add(password);
            param.Add(model);
            param.Add("read");
            param.Add(new List<object> { domain, fields });
            //param.Add(pageData);
            JObject data = null;
            try
            {
                data = await Call("object", "execute_kw", param);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"获取aMES数据失败，请求内容：{JsonConvert.SerializeObject(param)}，错误信息：{ex.Message}");
                throw new AppException(ex.ToString());
            }
            Console.WriteLine(data);
            return data;
        }
        public async Task<JObject> Get_stoke_(string model, List<object> domain, List<string> fields, object pageData)
        {
            Console.WriteLine("AAAAAAAAA");
            var param = new List<object>();
            param.Add(db);
            //if (uid == null || uid == 0)
                uid = await GetOdooUid(userName, password);
            Console.WriteLine(uid);
            param.Add(uid);
            param.Add(password);
            param.Add(model);
            param.Add("search_read");
            param.Add(new List<object> { domain, fields });
            param.Add(pageData);
            JObject data = null;
            try
            {
                data = await Call("object", "execute_kw", param);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"获取aMES数据失败，请求内容：{JsonConvert.SerializeObject(param)}，错误信息：{ex.Message}");
                throw new AppException(ex.ToString());
            }
            return data;
        }
        public async Task<JObject> Get_web_search_read(string model,Dictionary<string, object> result)
        {
            Console.WriteLine("AAAAAAAAA");
            var param = new List<object>();
            param.Add(db);
            //if (uid == null || uid == 0)
            uid = await GetOdooUid(userName, password);
            Console.WriteLine(uid);
            

            // 验证输出
            //Console.WriteLine("Domain structure type: " + result["domain"].GetType().Name);
            //Console.WriteLine("Specification keys: " + string.Join(", ", specification.Keys));

            param.Add(uid);
            param.Add(password);
            param.Add(model);
            param.Add("web_search_read");
            param.Add(new List<object> {});
            param.Add(result);
            //param.Add(pageData);
            JObject data = null;
            try
            {
                data = await Call("object", "execute_kw", param);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"获取aMES数据失败，请求内容：{JsonConvert.SerializeObject(param)}，错误信息：{ex.Message}");
                throw new AppException(ex.ToString());
            }
            return data;
        }
        public async Task<JObject> Get_web_read(string model, int id)
        {
            Console.WriteLine("wwwwww");
            var param = new List<object>();
            param.Add(db);
            //if (uid == null || uid == 0)
            uid = await GetOdooUid(userName, password);
            param.Add(uid);
            param.Add(password);
            param.Add(model);
            param.Add("web_read");
            param.Add(new List<object> { id });
            var specification_ = new Dictionary<string, object>
            {
                { "weight", new Dictionary<string, object>() }
            };
            var result = new Dictionary<string, object>
                {
                    { "specification", specification_ }
                };
            param.Add(result);
            JObject data = null;
            try
            {
                data = await Call("object", "execute_kw", param);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"获取aMES数据失败，请求内容：{JsonConvert.SerializeObject(param)}，错误信息：{ex.Message}");
                throw new AppException(ex.ToString());
            }
            Console.WriteLine(data);
            return data;
        }

        public async Task<JObject> Get_web_read_all(string model, int id, Dictionary<string, object> result)
        {
            Console.WriteLine("wwwwww");
            var param = new List<object>();
            param.Add(db);
            //if (uid == null || uid == 0)
            uid = await GetOdooUid(userName, password);
            param.Add(uid);
            param.Add(password);
            param.Add(model);
            param.Add("web_read");
            param.Add(new List<object> { new List<object> { id } });
            //var specification_ = new Dictionary<string, object>
            //{
            //    { "weight", new Dictionary<string, object>() }
            //};
            //var result = new Dictionary<string, object>
            //    {
            //        { "specification", specification_ }
            //    };
            param.Add(result);
            JObject data = null;
            try
            {
                data = await Call("object", "execute_kw", param);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"获取aMES数据失败，请求内容：{JsonConvert.SerializeObject(param)}，错误信息：{ex.Message}");
                throw new AppException(ex.ToString());
            }
            Console.WriteLine(data);
            return data;
        }



        /// <summary>
        /// 同步生产任务单
        /// </summary>
        /// 

        public async Task<JObject> Get_info_gzd(string model, List<object> domain, List<string> fields, object pageData)
        {
            Console.WriteLine("AAAAAAAAA");
            var param = new List<object>();
            param.Add(db);
            //if (uid == null || uid == 0)
                uid = await GetOdooUid(userName, password);
            Console.WriteLine(uid);
            param.Add(uid);
            param.Add(password);
            param.Add(model);
            param.Add("search_read");
            param.Add(new List<object> { domain, fields });
            param.Add(pageData);
            JObject data = null;
            try
            {
                data = await Call("object", "execute_kw", param);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"获取aMES数据失败，请求内容：{JsonConvert.SerializeObject(param)}，错误信息：{ex.Message}");
                throw new AppException(ex.ToString());
            }
            return data;
        }

        public async Task<JObject> name_research(string model, object domain)
        {
            Console.WriteLine("AAAAAAAAA");
            var param = new List<object>();
            param.Add(db);
            //if (uid == null || uid == 0)
            uid = await GetOdooUid(userName, password);
            Console.WriteLine(uid);
            param.Add(uid);
            param.Add(password);
            param.Add(model);
            param.Add("name_search");
            param.Add(new List<object>());
            param.Add(domain);
            //param.Add(pageData);
            JObject data = null;
            try
            {
                data = await Call("object", "execute_kw", param);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"获取aMES数据失败，请求内容：{JsonConvert.SerializeObject(param)}，错误信息：{ex.Message}");
                throw new AppException(ex.ToString());
            }
            return data;
        }

        public async Task<JObject> Get_info_YFpro(string model, List<object> domain, List<string> fields, object pageData)
        {
            Console.WriteLine("AAAAAAAAA");
            var param = new List<object>();
            param.Add(db);
            //if (uid == null || uid == 0)
            uid = await GetOdooUid(userName, password);
            Console.WriteLine(uid);
            param.Add(uid);
            param.Add(password);
            param.Add(model);
            param.Add("search_read");
            param.Add(new List<object> { domain, fields });
            param.Add(pageData);
            JObject data = null;
            try
            {
                data = await Call("object", "execute_kw", param);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"获取aMES数据失败，请求内容：{JsonConvert.SerializeObject(param)}，错误信息：{ex.Message}");
                throw new AppException(ex.ToString());
            }
            return data;
        }

        public async Task<JObject> Get_name_id(string model, List<object> domain, List<string> fields, object pageData)
        {
            Console.WriteLine("AAAAAAAAA");
            var param = new List<object>();
            param.Add(db);
            //if (uid == null || uid == 0)
                uid = await GetOdooUid(userName, password);
            Console.WriteLine(uid);
            param.Add(uid);
            param.Add(password);
            param.Add(model);
            param.Add("search_read");
            param.Add(new List<object> { domain, fields });
            param.Add(pageData);
            JObject data = null;
            try
            {
                data = await Call("object", "execute_kw", param);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"获取aMES数据失败，请求内容：{JsonConvert.SerializeObject(param)}，错误信息：{ex.Message}");
                throw new AppException(ex.ToString());
            }
            return data;
        }

        public async Task<object> SyncProductionTask(string taskNo = "")
        {
            var isSingle = taskNo.IsValuable();

            //同步的任务工序
            var typeArray = new[] { "powder" };
            //var typeArray = new[] { "white" };

            var qDomain = new List<object> {

                new List<object> { "production_type", "in", typeArray }
            };

            if (isSingle)
            {
                qDomain.Add(new List<object> { "name", "=", taskNo });
            }
            else
            {
                qDomain.Add(new List<object> { "state", "=", "in_production" });
            }

            var qFields = new List<string> {
                "grade",
                "prodcut_spec",
                "raw_resume_weight",
                "raw_resume_qty",
                "state",
                "schedule_id",
                "product_id",
                "partner_id",
                "name",
                "raw_lot_id",
                "date_planned",
                "product_qty",
                "production_type",
                "routing_id",
            };
            var qPage = new
            {
                limit = 10000,
                offset = 0,
                order = "name desc",
            };

            var resp = await CallSearchRead("mrp.production", qDomain, qFields, qPage);
            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];
            if (res == null || res.Count <= 0)
            {
                return null;
            }
            var r = new List<object>();
            for (var i = 0; i < res.Count; i++)
            {
                var x = (JObject)res[i];
                r.Add(new
                {
                    WorkOrder = x["name"].ToString(),
                    Product = x["product_id"] is JArray ? JArray.FromObject(x["product_id"])[1].ToString() : "",
                    Qty = x["product_qty"].ToString(),
                    LotNo = x["raw_lot_id"] is JArray ? JArray.FromObject(x["raw_lot_id"])[1].ToString() : "",
                    SendTime = x["date_planned"].ToString().Substring(0, 10),
                    SendWeight = x["raw_resume_weight"].ToString(),
                    SendQty = x["raw_resume_qty"].ToString()
                });
            }
            return new
            {
                rows = r,
                total = res.Count
            };
        }

        public async Task<JObject> up_to_messys_wgjy(string model, int id_order, JObject result_data_final)
        {
            Console.WriteLine("AAAAAAAAA");
            var param = new List<object>();
            param.Add(db);
            //if (uid == null || uid == 0)
                uid = await GetOdooUid(userName, password);
            Console.WriteLine(uid);
            param.Add(uid);
            param.Add(password);
            param.Add(model);
            param.Add("write");
            List<object> aa = new List<object> { };
            aa.Add(id_order);
            aa.Add(result_data_final);
            //param.Add(new List<object> { id_order});
            param.Add(aa);
            JObject data = null;
            try
            {
                data = await Call("object", "execute_kw", param);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"获取aMES数据失败，请求内容：{JsonConvert.SerializeObject(param)}，错误信息：{ex.Message}");
                throw new AppException(ex.ToString());
            }
            return data;
        }
        public async Task<JObject> up_to_messys(string model, int id_order, Dictionary<string, object> result_data_final)
        {
            Console.WriteLine("AAAAAAAAA");
            var param = new List<object>();
            param.Add(db);
            //if (uid == null || uid == 0)
                uid = await GetOdooUid(userName, password);
            Console.WriteLine(uid);
            param.Add(uid);
            param.Add(password);
            param.Add(model);
            param.Add("write");
            List<object> aa = new List<object> { };
            aa.Add(id_order);
            aa.Add(result_data_final);
            //param.Add(new List<object> { id_order});
            param.Add(aa);
            JObject data = null;
            try
            {
                data = await Call("object", "execute_kw", param);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"获取aMES数据失败，请求内容：{JsonConvert.SerializeObject(param)}，错误信息：{ex.Message}");
                throw new AppException(ex.ToString());
            }
            return data;
        }
        public async Task<JObject> done_to_messys(string model, int id_order)
        {
            Console.WriteLine("AAAAAAAAA");
            var param = new List<object>();
            param.Add(db);
            //if (uid == null || uid == 0)
            uid = await GetOdooUid(userName, password);
            Console.WriteLine(uid);
            param.Add(uid);
            param.Add(password);
            param.Add(model);
            param.Add("do_done");
            param.Add(new List<object> { id_order });
            JObject data = null;
            try
            {
                data = await Call("object", "execute_kw", param);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"获取aMES数据失败，请求内容：{JsonConvert.SerializeObject(param)}，错误信息：{ex.Message}");
                throw new AppException(ex.ToString());
            }
            return data;
        }


        /// <summary>
        /// 根据投料批次获取任务单信息
        /// </summary>
        /// <param name="taskNo"></param>
        /// <returns></returns>
        /// <exception cref="AppException"></exception>
        public async Task<dynamic> GetProductionTaskByMatLot(string lotno = "")
        {
            //同步的任务工序
            var typeArray = new[] { "final" };

            var qDomain = new List<object> {
                new List<object> { "production_type", "in", typeArray },
                new List<object> { "raw_lot_id", "=", lotno }
            };


            var qFields = new List<string> {
                "grade",
                "prodcut_spec",
                "raw_resume_weight",
                "raw_resume_qty",
                "state",
                "schedule_id",
                "product_id",
                "partner_id",
                "name",
                "raw_lot_id",
                "date_planned",
                "product_qty",
                "production_type",
                "routing_id",
            };
            var qPage = new
            {
                limit = 10000,
                offset = 0,
                order = "name desc",
            };

            var resp = await CallSearchRead("mrp.production", qDomain, qFields, qPage);
            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];
            if (res == null || res.Count <= 0)
            {
                return null;
            }
            return res[0];
        }

        /// <summary>
        /// 获取北京空港10.7.1.3中仓库-库存查看-原料库中的所有数据
        /// </summary>
        /// 
        public async Task<List<ResultAdd>> SyncMaterialInventory_KongGang()
        {
            var qDomain = new List<object> {
                //网页开发者模式中Payload中的domain
                new List<object> { "location_id", "child_of", 1481 }
            };
            

            var qFields = new List<string> {
                "nc_code",
                "product_id",
                "product_uom_id",
                "qty"
            };
            var qPage = new
            {
                context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
                limit = 10000,
                offset = 0,
            };

            var resp = await CallSearchRead("stock.quant", qDomain, qFields, qPage);

            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];

            if (res == null || res.Count <= 0)
            {
                return null;
            }
            var r = new List<ResultAdd>();

            for (var i = 0; i < res.Count; i++)
            {
                var x = (JObject)res[i];
                //通过nc编码在物资中找到其在途数量(1.获取物资中的id  2.通过id在详细页面中找在途数量)
                string nc_code = x["nc_code"].ToString();
                var qDomain2 = new List<object> {
                new List<object> { "top_id", "=", false },
                new List<object> { "trade_ok", "=", false },
                new List<object> { "nc_code", "=", nc_code },
                };
                var qFields2 = new List<string> {"id"};
                //1
                var resp2 = await CallSearchRead("product.template", qDomain2, qFields2, qPage);
                var res2 = (JArray)resp2["result"];
                decimal incoming_qty = 0;
                if (res2.Count == 0 || res2 == null)
                {
                    incoming_qty = -1;
                }
                else
                {
                    var y = (JObject)res2[0];
                    int id = (int)y["id"];
                    //2
                    var qDomain3 = new List<object> { id };
                    var qFields3 = new List<string> { "incoming_qty" };
                    var resp3 = await CallRead("product.template", qDomain3, qFields3, qPage);
                    var res3 = (JArray)resp3["result"];
                    var z = (JObject)res3[0];
                    incoming_qty = (decimal)z["incoming_qty"];
                }


                r.Add(new ResultAdd
                {
                    //nc_code = x["nc_code"].ToString(),
                    ProductId = x["product_id"] is JArray ? JArray.FromObject(x["product_id"])[1].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                    //product_uom_id = x["product_uom_id"] is JArray ? JArray.FromObject(x["product_uom_id"])[1].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                    Qty = (decimal)x["qty"],
                    IncomingQty = incoming_qty,

                });

            }
            return r;
        }
        public class ResultAdd
        {
            public string ProductId { get; set; }
            public string Lot { get; set; }
            public decimal Qty { get; set; }
            public decimal IncomingQty { get; set; }
            public string Grade { get; set; }
            public string Spec { get; set; }
            public decimal Br { get; set; } 
            public decimal Hcj { get; set; }
            public string Location { get; set; }
            public int InventoryAge { get; set; }
            public int Id { get; set; }
            public string Cate1 { get; set; }
            public string Cate2 { get; set; }
            public string UserId { get; set; }
            public string PoDate { get; set; }
            public string PartnerId { get; set; }
            public string Name { get; set; }
            public string Code { get; set; }
            public decimal ProductQty { get; set; }
            public decimal PriceUint { get; set; }
            public decimal BasePrice { get; set; }
            public decimal PriceSubtotal { get; set; }
            public decimal Total { get; set; }
            public string ProductUom { get; set; }

        }

        public async Task<List<ResultAdd>> SyncMaterialInventory_AiKe()
        {
            var qDomain = new List<object> {
                //网页开发者模式中Payload中的domain
                new List<object> { "location_id", "child_of", 1481 }
            };

            var qFields = new List<string> {
                "nc_code",
                "product_id",
                "product_uom_id",
                "qty"
            };
            var qPage = new
            {
                context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
                limit = 10000,
                offset = 0,
            };

            var resp = await CallSearchRead_AiKe("stock.quant", qDomain, qFields, qPage);

            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];

            if (res == null || res.Count <= 0)
            {
                return null;
            }
            var r = new List<ResultAdd>();

            for (var i = 0; i < res.Count; i++)
            {
                var x = (JObject)res[i];
                //通过nc编码在物资中找到其在途数量(1.获取物资中的id  2.通过id在详细页面中找在途数量)
                string nc_code = x["nc_code"].ToString();
                var qDomain2 = new List<object> {
                new List<object> { "top_id", "=", false },
                new List<object> { "trade_ok", "=", false },
                new List<object> { "nc_code", "=", nc_code },
                };
                var qFields2 = new List<string> { "id" }; 
                Console.WriteLine(nc_code);
                Console.WriteLine(x["product_id"].ToString());
                //1
                var resp2 = await CallSearchRead_AiKe("product.template", qDomain2, qFields2, qPage);
                var res2 = (JArray)resp2["result"];
                Console.WriteLine("1111111111111111111111111111111111");
                Console.WriteLine(resp2);
                decimal incoming_qty = 0;
                if (res2.Count == 0 || res2 == null)
                {
                    incoming_qty = -1;
                }
                else
                {
                    
                    var y = (JObject)res2[0];
                    int id = (int)y["id"];
                    //2
                    var qDomain3 = new List<object> { id };
                    var qFields3 = new List<string> { "incoming_qty" };
                    var resp3 = await CallRead_AiKe("product.template", qDomain3, qFields3, qPage);
                    var res3 = (JArray)resp3["result"];
                    if (res3.Count == 0 || res3 == null)
                    {
                        incoming_qty = -1;
                    }
                    else
                    {
                        var z = (JObject)res3[0];
                        incoming_qty = (decimal)z["incoming_qty"];
                    }
                    
                }

                r.Add(new ResultAdd
                {
                    //nc_code = x["nc_code"].ToString(),
                    ProductId = x["product_id"] is JArray ? JArray.FromObject(x["product_id"])[1].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                    //product_uom_id = x["product_uom_id"] is JArray ? JArray.FromObject(x["product_uom_id"])[1].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                    Qty = (decimal)x["qty"],
                    IncomingQty = incoming_qty,
                });

            }
            return r;
        }

        public async Task<List<ResultAdd>> SyncMaterialInventory_BeiFang(string location)
        {
            var qDomain = new List<object>(); // 先声明变量，但不初始化

            if (location == "beifang")
            {
                qDomain = new List<object>
                {
                    new List<object> { "location_id", "child_of", 1481 }
                };
            }
            else if (location == "ningbo")
            {
                qDomain = new List<object>
                {
                    new List<object> { "location_id", "child_of", 27229 }
                };
            }

            var qFields = new List<string> {
                "nc_code",
                "product_id",
                "product_uom_id",
                "location_id",
                "quantity"
            };
            var qPage = new
            {
                context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
                limit = 10000,
                offset = 0,
            };

           var resp = await CallSearchRead_BeiFang("stock.quant", qDomain, qFields, qPage);

            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];

            if (res == null || res.Count <= 0)
            {
                return null;
            }
            var r = new List<ResultAdd>();

            for (var i = 0; i < res.Count; i++)
            {
                var x = (JObject)res[i];
                //通过nc编码在物资中找到其在途数量(1.获取物资中的id  2.通过id在详细页面中找在途数量)
                string nc_code = x["nc_code"].ToString();
                var qDomain2 = new List<object> {
                new List<object> { "top_id", "=", false },
                new List<object> { "trade_ok", "=", false },
                new List<object> { "nc_code", "=", nc_code },
                };
                var qFields2 = new List<string> { "id" };
                //1
                var resp2 = await CallSearchRead_BeiFang("product.template", qDomain2, qFields2, qPage);
                decimal incoming_qty = 0;
                if (resp2.ContainsKey("error"))
                {
                    incoming_qty = 0;
                }
                else
                {
                    var res2 = (JArray)resp2["result"];
                    var y = (JObject)res2[0];
                    int id = (int)y["id"];
                    //2
                    var qDomain3 = new List<object> { id };
                    var qFields3 = new List<string> { "incoming_qty" };
                    var resp3 = await CallRead_BeiFang("product.template", qDomain3, qFields3, qPage);
                    var res3 = (JArray)resp3["result"];
                    var z = (JObject)res3[0];
                    incoming_qty = (decimal)z["incoming_qty"];
                }
                
                r.Add(new ResultAdd
                {
                    //nc_code = x["nc_code"]?.ToString(),
                    //productId = x["product_id"] is JArray ? JArray.FromObject(x["product_id"])[display_name].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                    ProductId = x["product_id"]?[1]?.ToString(),
                    //product_uom_id = x["product_uom_id"]?[1]?.ToString(),
                    //product_uom_id = x["product_uom_id"] is JArray ? JArray.FromObject(x["product_uom_id"])[0].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                    Qty = (decimal)x["quantity"],
                    IncomingQty = incoming_qty,
                });

            }
            return r;
        }

        public async Task SyncMaterialInventory_Deal(List<ResultAdd> r1, List<ResultAdd> r2, List<ResultAdd> r3, List<ResultAdd> r4)
        {
            if (r1 is null || r2 is null || r3 is null || r4 is null)
            {
                throw new ArgumentNullException(nameof(r1));
                throw new ArgumentNullException(nameof(r2));
                throw new ArgumentNullException(nameof(r3));
                throw new ArgumentNullException(nameof(r4));
            }
            // 从Material_Zhenghe数据表中获取所有数据
            var res = await Db.Set<Material_Zhenghe>().ToListAsync();
            var r = new List<Material_Look>();
            r1.ForEach(x => {
                // 将r1中的产品代码与从Material_Zhenghe数据表中获取到的产品代码对比，返回符合的Material_Zhenghe中的数据
                var tmp = res.Where(i => i.ProductIdKg == x.ProductId).FirstOrDefault();
                //if (tmp == null) throw new AppException($"{x.ProductId}找不到对应的统称");
                r.Add(new Material_Look
                {
                    //tmp是从数据库中获取的数据
                    ProductId = tmp?.ProductId,
                    ProductIdKg = x.ProductId,
                    ProductIdSd = tmp?.ProductIdSd,
                    ProductIdBf = tmp?.ProductIdBf,
                    ProductIdNb = tmp?.ProductIdBf,
                    QtyKg = x.Qty,
                    IncomingQtyKg = x.IncomingQty,
                    Qty = x.Qty
                });
            });

            r2.ForEach(x => {
                var tmp = res.Where(i => i.ProductIdSd == x.ProductId).FirstOrDefault();
                //if (tmp == null) throw new AppException($"{x.ProductId}找不到对应的统称");
                r.Add(new Material_Look
                {
                    ProductId = tmp?.ProductId,
                    ProductIdSd = x.ProductId,
                    ProductIdKg = tmp?.ProductIdKg,
                    ProductIdBf = tmp?.ProductIdBf,
                    ProductIdNb = tmp?.ProductIdBf,
                    QtySd = x.Qty,
                    IncomingQtySd = x.IncomingQty,
                    Qty = x.Qty
                });
            });

            r3.ForEach(x => {
                var tmp = res.Where(i => i.ProductIdBf == x.ProductId).FirstOrDefault();
                //if (tmp == null) throw new AppException($"{x.ProductId}找不到对应的统称");
                r.Add(new Material_Look
                {
                    ProductId = tmp?.ProductId,
                    ProductIdBf = x.ProductId,
                    ProductIdSd = tmp?.ProductIdSd,
                    ProductIdKg = tmp?.ProductIdKg,
                    ProductIdNb = tmp?.ProductIdBf,
                    QtyBf = x.Qty,
                    IncomingQtyBf = x.IncomingQty,
                    Qty = x.Qty
                });
            });
            r4.ForEach(x =>
            {
                var tmp = res.Where(i => i.ProductIdBf == x.ProductId).FirstOrDefault();
                //if (tmp == null) throw new AppException($"{x.ProductId}找不到对应的统称");
                r.Add(new Material_Look
                {
                    ProductId = tmp?.ProductId,
                    ProductIdNb = x.ProductId,
                    ProductIdSd = tmp?.ProductIdSd,
                    ProductIdKg = tmp?.ProductIdKg,
                    ProductIdBf = tmp?.ProductIdBf,
                    QtyNb = x.Qty,
                    IncomingQtyNb = x.IncomingQty,
                    Qty = x.Qty
                });
            });
            //将数据进行整合，重复的数量进行累加，合并成一条
            var data = r.GroupBy(x => x.ProductId).Select(x => new Material_Look
            {
                ProductId = x.Key,
                Qty = x.Sum(x => x.Qty),
                ProductIdKg = x.Min(x => x.ProductIdKg),
                ProductIdSd = x.Min(x => x.ProductIdSd),
                ProductIdBf = x.Min(x => x.ProductIdBf),
                ProductIdNb = x.Min(x => x.ProductIdNb),
                QtyKg = x.Sum(x => x.QtyKg),
                QtySd = x.Sum(x => x.QtySd),
                QtyBf = x.Sum(x => x.QtyBf),
                QtyNb = x.Sum(x => x.QtyNb),
                IncomingQtyKg = x.Min(x => x.IncomingQtyKg) ?? 0,
                IncomingQtySd = x.Min(x => x.IncomingQtySd) ?? 0,
                IncomingQtyBf = x.Min(x => x.IncomingQtyBf) ?? 0,
                IncomingQtyNb = x.Min(x => x.IncomingQtyNb) ?? 0,
                IncomingQty = x.Min(x => x.IncomingQtyKg) ?? 0 + x.Min(x => x.IncomingQtySd) ?? 0 + x.Min(x => x.IncomingQtyBf) ?? 0 + x.Min(x => x.IncomingQtyNb) ?? 0

            }).ToList();

            await Db.DoDeleteAsync<Material_Look>(x=>x.IsValid >= 0, true);
            await Db.DoInsertAsync<Material_Look>(data);
        }

        public async Task<List<ResultAdd>> SyncChemistrylInventory_KongGang()
        {
            var qDomain = new List<object> {
                //网页开发者模式中Payload中的domain
                new List<object> { "location_id", "child_of", 9506 }
            };

            var qFields = new List<string> {
                "nc_code",
                "product_id",
                "product_uom_id",
                "qty"
            };
            var qPage = new
            {
                context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
                limit = 10000,
                offset = 0,
                order = "product_id desc",
            };

            var resp = await CallSearchRead("stock.quant", qDomain, qFields, qPage);

            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];

            if (res == null || res.Count <= 0)
            {
                return null;
            }
            var r = new List<ResultAdd>();

            for (var i = 0; i < res.Count; i++)
            {
                var x = (JObject)res[i];
                r.Add(new ResultAdd
                {
                    //nc_code = x["nc_code"].ToString(),
                    ProductId = x["product_id"] is JArray ? JArray.FromObject(x["product_id"])[1].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                    //product_uom_id = x["product_uom_id"] is JArray ? JArray.FromObject(x["product_uom_id"])[1].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                    Qty = (decimal)x["qty"],

                });

            }
            return r;
        }

        public async Task<List<ResultAdd>> SyncChemistryInventory_AiKe()
        {
            var qDomain = new List<object> {
                //网页开发者模式中Payload中的domain
                new List<object> { "location_id", "child_of", 7598 }
            };

            var qFields = new List<string> {
                "nc_code",
                "product_id",
                "product_uom_id",
                "qty"
            };
            var qPage = new
            {
                context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
                limit = 10000,
                offset = 0,
                order = "name desc",
            };

            var resp = await CallSearchRead_AiKe("stock.quant", qDomain, qFields, qPage);

            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];

            if (res == null || res.Count <= 0)
            {
                return null;
            }
            var r = new List<ResultAdd>();

            for (var i = 0; i < res.Count; i++)
            {
                var x = (JObject)res[i];
                r.Add(new ResultAdd
                {
                    //nc_code = x["nc_code"].ToString(),
                    ProductId = x["product_id"] is JArray ? JArray.FromObject(x["product_id"])[1].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                    //product_uom_id = x["product_uom_id"] is JArray ? JArray.FromObject(x["product_uom_id"])[1].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                    Qty = (decimal)x["qty"],

                });

            }
            return r;
        }

        public async Task<List<ResultAdd>> SyncChemistryInventory_BeiFang(string location)
        {
            var qDomain = new List<object>(); // 先声明变量，但不初始化

            if (location == "beifang")
            {
                qDomain = new List<object>
                {
                    new List<object> { "location_id", "child_of", 7598 }
                };
            }
            else if (location == "ningbo")
            {
                qDomain = new List<object>
                {
                    new List<object> { "location_id", "child_of", 27229 }
                };
            }

            var qFields = new List<string> {
                "nc_code",
                "product_id",
                "product_uom_id",
                "quantity"
            };
            var qPage = new
            {
                context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
                limit = 10000,
                offset = 0,
                order = "product_id desc",
            };

            var resp = await CallSearchRead_BeiFang("stock.quant", qDomain, qFields, qPage);

            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];

            if (res == null || res.Count <= 0)
            {
                return null;
            }
            var r = new List<ResultAdd>();

            for (var i = 0; i < res.Count; i++)
            {
                var x = (JObject)res[i];
                r.Add(new ResultAdd
                {
                    //nc_code = x["nc_code"]?.ToString(),
                    //productId = x["product_id"] is JArray ? JArray.FromObject(x["product_id"])[display_name].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                    ProductId = x["product_id"]?[1]?.ToString(),
                    //product_uom_id = x["product_uom_id"]?[1]?.ToString(),
                    //product_uom_id = x["product_uom_id"] is JArray ? JArray.FromObject(x["product_uom_id"])[0].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                    Qty = (decimal)x["quantity"],

                });

            }
            return r;
        }

        public async Task SyncChemistryInventory_Deal(List<ResultAdd> r1, List<ResultAdd> r3)
        {
            if (r1 is null  || r3 is null )
            {
                throw new ArgumentNullException(nameof(r1));
                //throw new ArgumentNullException(nameof(r2));
                throw new ArgumentNullException(nameof(r3));

            }
            // 从Material_Zhenghe数据表中获取所有数据
            var res = await Db.Set<Chemistry_Zhenghe>().ToListAsync();
            var r = new List<Chemistry_Look>();
            r1.ForEach(x => {
                // 将r1中的产品代码与从Material_Zhenghe数据表中获取到的产品代码对比，返回符合的Material_Zhenghe中的数据
                var tmp = res.Where(i => i.ProductIdKg == x.ProductId).FirstOrDefault();
                //if (tmp == null) throw new AppException($"{x.ProductId}找不到对应的统称");
                r.Add(new Chemistry_Look
                {
                    //tmp是从数据库中获取的数据
                    ProductId = tmp?.ProductId,
                    ProductIdKg = x.ProductId,
                    ProductIdSd = tmp?.ProductIdSd,
                    ProductIdBf = tmp?.ProductIdBf,
                    ProductIdNb = tmp?.ProductIdBf,
                    QtyKg = x.Qty,
                    Qty = x.Qty
                });
            });

            //r2.ForEach(x => {
            //    var tmp = res.Where(i => i.ProductIdSd == x.ProductId).FirstOrDefault();
            //    //if (tmp == null) throw new AppException($"{x.ProductId}找不到对应的统称");
            //    r.Add(new Chemistry_Look
            //    {
            //        ProductId = tmp?.ProductId,
            //        ProductIdSd = x.ProductId,
            //        ProductIdKg = tmp?.ProductIdKg,
            //        ProductIdBf = tmp?.ProductIdBf,
            //        ProductIdNb = tmp?.ProductIdBf,
            //        QtySd = x.Qty,
            //        Qty = x.Qty
            //    });
            //});

            r3.ForEach(x => {
                var tmp = res.Where(i => i.ProductIdBf == x.ProductId).FirstOrDefault();
                //if (tmp == null) throw new AppException($"{x.ProductId}找不到对应的统称");
                r.Add(new Chemistry_Look
                {
                    ProductId = tmp?.ProductId,
                    ProductIdBf = x.ProductId,
                    ProductIdSd = tmp?.ProductIdSd,
                    ProductIdKg = tmp?.ProductIdKg,
                    ProductIdNb = tmp?.ProductIdBf,
                    QtyBf = x.Qty,
                    Qty = x.Qty
                });
            });
            //r4.ForEach(x =>
            //{
            //    var tmp = res.Where(i => i.ProductIdBf == x.ProductId).FirstOrDefault();
            //    //if (tmp == null) throw new AppException($"{x.ProductId}找不到对应的统称");
            //    r.Add(new Chemistry_Look
            //    {
            //        ProductId = tmp?.ProductId,
            //        ProductIdNb = x.ProductId,
            //        ProductIdSd = tmp?.ProductIdSd,
            //        ProductIdKg = tmp?.ProductIdKg,
            //        ProductIdBf = tmp?.ProductIdBf,
            //        QtyNb = x.Qty,
            //        Qty = x.Qty
            //    });
            //});
            //将数据进行整合，重复的数量进行累加，合并成一条
            var data = r.GroupBy(x => x.ProductId).Select(x => new Chemistry_Look
            {
                ProductId = x.Key,
                Qty = x.Sum(x => x.Qty),
                ProductIdKg = x.Min(x => x.ProductIdKg),
                ProductIdSd = x.Min(x => x.ProductIdSd),
                ProductIdBf = x.Min(x => x.ProductIdBf),
                ProductIdNb = x.Min(x => x.ProductIdNb),
                QtyKg = x.Sum(x => x.QtyKg),
                QtySd = x.Sum(x => x.QtySd),
                QtyBf = x.Sum(x => x.QtyBf),
                QtyNb = x.Sum(x => x.QtyNb),

            }).ToList();

            await Db.DoDeleteAsync<Chemistry_Look>(x => x.IsValid >= 0, true);
            await Db.DoInsertAsync<Chemistry_Look>(data);
            //await Db.DoInsertAsync<Chemistry_Look>(r);
        }

        public async Task<List<ResultAdd>> SyncPackageInventory_KongGang()
        {
            var qDomain = new List<object> {
                //网页开发者模式中Payload中的domain
                new List<object> { "location_id", "child_of", 9512 }
            };

            var qFields = new List<string> {
                "nc_code",
                "product_id",
                "product_uom_id",
                "qty"
            };
            var qPage = new
            {
                context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
                limit = 10000,
                offset = 0,
            };

            var resp = await CallSearchRead("stock.quant", qDomain, qFields, qPage);

            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];

            if (res == null || res.Count <= 0)
            {
                return null;
            }
            var r = new List<ResultAdd>();

            for (var i = 0; i < res.Count; i++)
            {
                var x = (JObject)res[i];
                r.Add(new ResultAdd
                {
                    //nc_code = x["nc_code"].ToString(),
                    ProductId = x["product_id"] is JArray ? JArray.FromObject(x["product_id"])[1].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                    //product_uom_id = x["product_uom_id"] is JArray ? JArray.FromObject(x["product_uom_id"])[1].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                    Qty = (decimal)x["qty"],

                });

            }
            return r;
        }

        public async Task<List<ResultAdd>> SyncPackageInventory_AiKe()
        {
            var qDomain = new List<object> {
                //网页开发者模式中Payload中的domain
                new List<object> { "location_id", "child_of", 7598 }
            };

            var qFields = new List<string> {
                "nc_code",
                "product_id",
                "product_uom_id",
                "qty"
            };
            var qPage = new
            {
                context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
                limit = 10000,
                offset = 0,
                order = "name desc",
            };

            var resp = await CallSearchRead_AiKe("stock.quant", qDomain, qFields, qPage);

            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];

            if (res == null || res.Count <= 0)
            {
                return null;
            }
            var r = new List<ResultAdd>();

            for (var i = 0; i < res.Count; i++)
            {
                var x = (JObject)res[i];
                r.Add(new ResultAdd
                {
                    //nc_code = x["nc_code"].ToString(),
                    ProductId = x["product_id"] is JArray ? JArray.FromObject(x["product_id"])[1].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                    //product_uom_id = x["product_uom_id"] is JArray ? JArray.FromObject(x["product_uom_id"])[1].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                    Qty = (decimal)x["qty"],

                });

            }
            return r;
        }

        public async Task<List<ResultAdd>> SyncPackageInventory_BeiFang(string location)
        {
            var qDomain = new List<object>(); // 先声明变量，但不初始化

            if (location == "beifang")
            {
                qDomain = new List<object>
                {
                    new List<object> { "location_id", "child_of", 7604 }
                };
            }
            else if (location == "ningbo")
            {
                qDomain = new List<object>
                {
                    new List<object> { "location_id", "child_of", 27229 }
                };
            }

            var qFields = new List<string> {
                "nc_code",
                "product_id",
                "product_uom_id",
                "quantity"
            };
            var qPage = new
            {
                context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
                limit = 10000,
                offset = 0,
                order = "product_id desc",
            };

            var resp = await CallSearchRead_BeiFang("stock.quant", qDomain, qFields, qPage);

            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];

            if (res == null || res.Count <= 0)
            {
                return null;
            }
            var r = new List<ResultAdd>();

            for (var i = 0; i < res.Count; i++)
            {
                var x = (JObject)res[i];
                r.Add(new ResultAdd
                {
                    //nc_code = x["nc_code"]?.ToString(),
                    //productId = x["product_id"] is JArray ? JArray.FromObject(x["product_id"])[display_name].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                    ProductId = x["product_id"]?[1]?.ToString(),
                    //product_uom_id = x["product_uom_id"]?[1]?.ToString(),
                    //product_uom_id = x["product_uom_id"] is JArray ? JArray.FromObject(x["product_uom_id"])[0].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                    Qty = (decimal)x["quantity"],

                });

            }
            return r;
        }

        public async Task SyncPackageInventory_Deal(List<ResultAdd> r1, List<ResultAdd> r3)
        {
            if (r1 is null || r3 is null)
            {
                throw new ArgumentNullException(nameof(r1));
                //throw new ArgumentNullException(nameof(r2));
                throw new ArgumentNullException(nameof(r3));

            }
            // 从Material_Zhenghe数据表中获取所有数据
            var res = await Db.Set<Package_Zhenghe>().ToListAsync();
            var r = new List<Package_Look>();
            r1.ForEach(x => {
                // 将r1中的产品代码与从Material_Zhenghe数据表中获取到的产品代码对比，返回符合的Material_Zhenghe中的数据
                var tmp = res.Where(i => i.ProductIdKg == x.ProductId).FirstOrDefault();
                //if (tmp == null) throw new AppException($"{x.ProductId}找不到对应的统称");
                r.Add(new Package_Look
                {
                    //tmp是从数据库中获取的数据
                    ProductId = tmp?.ProductId,
                    ProductIdKg = x.ProductId,
                    ProductIdSd = tmp?.ProductIdSd,
                    ProductIdBf = tmp?.ProductIdBf,
                    ProductIdNb = tmp?.ProductIdBf,
                    QtyKg = x.Qty,
                    Qty = x.Qty
                });
            });

            //r2.ForEach(x => {
            //    var tmp = res.Where(i => i.ProductIdSd == x.ProductId).FirstOrDefault();
            //    //if (tmp == null) throw new AppException($"{x.ProductId}找不到对应的统称");
            //    r.Add(new Chemistry_Look
            //    {
            //        ProductId = tmp?.ProductId,
            //        ProductIdSd = x.ProductId,
            //        ProductIdKg = tmp?.ProductIdKg,
            //        ProductIdBf = tmp?.ProductIdBf,
            //        ProductIdNb = tmp?.ProductIdBf,
            //        QtySd = x.Qty,
            //        Qty = x.Qty
            //    });
            //});

            r3.ForEach(x => {
                var tmp = res.Where(i => i.ProductIdBf == x.ProductId).FirstOrDefault();
                //if (tmp == null) throw new AppException($"{x.ProductId}找不到对应的统称");
                r.Add(new Package_Look
                {
                    ProductId = tmp?.ProductId,
                    ProductIdBf = x.ProductId,
                    ProductIdSd = tmp?.ProductIdSd,
                    ProductIdKg = tmp?.ProductIdKg,
                    ProductIdNb = tmp?.ProductIdBf,
                    QtyBf = x.Qty,
                    Qty = x.Qty
                });
            });
            //r4.ForEach(x =>
            //{
            //    var tmp = res.Where(i => i.ProductIdBf == x.ProductId).FirstOrDefault();
            //    //if (tmp == null) throw new AppException($"{x.ProductId}找不到对应的统称");
            //    r.Add(new Chemistry_Look
            //    {
            //        ProductId = tmp?.ProductId,
            //        ProductIdNb = x.ProductId,
            //        ProductIdSd = tmp?.ProductIdSd,
            //        ProductIdKg = tmp?.ProductIdKg,
            //        ProductIdBf = tmp?.ProductIdBf,
            //        QtyNb = x.Qty,
            //        Qty = x.Qty
            //    });
            //});
            //将数据进行整合，重复的数量进行累加，合并成一条
            //var data = r.GroupBy(x => x.ProductId).Select(x => new Chemistry_Look
            //{
            //    ProductId = x.Key,
            //    Qty = x.Sum(x => x.Qty),
            //    ProductIdKg = x.Min(x => x.ProductIdKg),
            //    ProductIdSd = x.Min(x => x.ProductIdSd),
            //    ProductIdBf = x.Min(x => x.ProductIdBf),
            //    ProductIdNb = x.Min(x => x.ProductIdNb),
            //    QtyKg = x.Sum(x => x.QtyKg),
            //    QtySd = x.Sum(x => x.QtySd),
            //    QtyBf = x.Sum(x => x.QtyBf),
            //    QtyNb = x.Sum(x => x.QtyNb),

            //}).ToList();

            await Db.DoDeleteAsync<Package_Look>(x => x.IsValid >= 0, true);
            //await Db.DoInsertAsync<Chemistry_Look>(data);
            await Db.DoInsertAsync<Package_Look>(r);
        }

        public async Task<List<ResultAdd>> SyncAuxiliaryInventory_KongGang()
        {
            var qDomain = new List<object> {
                //网页开发者模式中Payload中的domain
                new List<object> { "location_id", "child_of", 9518 }
            };

            var qFields = new List<string> {
                "nc_code",
                "product_id",
                "product_uom_id",
                "qty"
            };
            var qPage = new
            {
                context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
                limit = 10000,
                offset = 0,
                order = "product_id desc",
            };

            var resp = await CallSearchRead("stock.quant", qDomain, qFields, qPage);

            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];

            if (res == null || res.Count <= 0)
            {
                return null;
            }
            var r = new List<ResultAdd>();

            for (var i = 0; i < res.Count; i++)
            {
                var x = (JObject)res[i];
                r.Add(new ResultAdd
                {
                    //nc_code = x["nc_code"].ToString(),
                    ProductId = x["product_id"] is JArray ? JArray.FromObject(x["product_id"])[1].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                    //product_uom_id = x["product_uom_id"] is JArray ? JArray.FromObject(x["product_uom_id"])[1].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                    Qty = (decimal)x["qty"],

                });

            }
            return r;
        }

        public async Task<List<ResultAdd>> SyncAuxiliaryInventory_AiKe()
        {
            var qDomain = new List<object> {
                //网页开发者模式中Payload中的domain
                new List<object> { "location_id", "child_of", 7598 }
            };

            var qFields = new List<string> {
                "nc_code",
                "product_id",
                "product_uom_id",
                "qty"
            };
            var qPage = new
            {
                context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
                limit = 10000,
                offset = 0,
                order = "name desc",
            };

            var resp = await CallSearchRead_AiKe("stock.quant", qDomain, qFields, qPage);

            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];

            if (res == null || res.Count <= 0)
            {
                return null;
            }
            var r = new List<ResultAdd>();

            for (var i = 0; i < res.Count; i++)
            {
                var x = (JObject)res[i];
                r.Add(new ResultAdd
                {
                    //nc_code = x["nc_code"].ToString(),
                    ProductId = x["product_id"] is JArray ? JArray.FromObject(x["product_id"])[1].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                    //product_uom_id = x["product_uom_id"] is JArray ? JArray.FromObject(x["product_uom_id"])[1].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                    Qty = (decimal)x["qty"],

                });

            }
            return r;
        }

        public async Task<List<ResultAdd>> SyncAuxiliaryInventory_BeiFang(string location)
        {
            var qDomain = new List<object>(); // 先声明变量，但不初始化

            if (location == "beifang")
            {
                qDomain = new List<object>
                {
                    new List<object> { "location_id", "child_of", 7610 }
                };
            }
            else if (location == "ningbo")
            {
                qDomain = new List<object>
                {
                    new List<object> { "location_id", "child_of", 27229 }
                };
            }

            var qFields = new List<string> {
                "nc_code",
                "product_id",
                "product_uom_id",
                "quantity"
            };
            var qPage = new
            {
                context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
                limit = 10000,
                offset = 0,
                order = "product_id desc",
            };

            var resp = await CallSearchRead_BeiFang("stock.quant", qDomain, qFields, qPage);

            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];

            if (res == null || res.Count <= 0)
            {
                return null;
            }
            var r = new List<ResultAdd>();

            for (var i = 0; i < res.Count; i++)
            {
                var x = (JObject)res[i];
                r.Add(new ResultAdd
                {
                    //nc_code = x["nc_code"]?.ToString(),
                    //productId = x["product_id"] is JArray ? JArray.FromObject(x["product_id"])[display_name].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                    ProductId = x["product_id"]?[1]?.ToString(),
                    //product_uom_id = x["product_uom_id"]?[1]?.ToString(),
                    //product_uom_id = x["product_uom_id"] is JArray ? JArray.FromObject(x["product_uom_id"])[0].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                    Qty = (decimal)x["quantity"],

                });

            }
            return r;
        }

        public async Task SyncAuxiliaryInventory_Deal(List<ResultAdd> r1, List<ResultAdd> r3)
        {
            if (r1 is null || r3 is null)
            {
                throw new ArgumentNullException(nameof(r1));
                //throw new ArgumentNullException(nameof(r2));
                throw new ArgumentNullException(nameof(r3));

            }
            // 从Material_Zhenghe数据表中获取所有数据
            var res = await Db.Set<Auxiliary_Zhenghe>().ToListAsync();
            var r = new List<Auxiliary_Look>();
            r1.ForEach(x => {
                // 将r1中的产品代码与从Material_Zhenghe数据表中获取到的产品代码对比，返回符合的Material_Zhenghe中的数据
                var tmp = res.Where(i => i.ProductIdKg == x.ProductId).FirstOrDefault();
                //if (tmp == null) throw new AppException($"{x.ProductId}找不到对应的统称");
                r.Add(new Auxiliary_Look
                {
                    //tmp是从数据库中获取的数据
                    ProductId = tmp?.ProductId,
                    ProductIdKg = x.ProductId,
                    ProductIdSd = tmp?.ProductIdSd,
                    ProductIdBf = tmp?.ProductIdBf,
                    ProductIdNb = tmp?.ProductIdBf,
                    QtyKg = x.Qty,
                    Qty = x.Qty
                });
            });

            //r2.ForEach(x => {
            //    var tmp = res.Where(i => i.ProductIdSd == x.ProductId).FirstOrDefault();
            //    //if (tmp == null) throw new AppException($"{x.ProductId}找不到对应的统称");
            //    r.Add(new Chemistry_Look
            //    {
            //        ProductId = tmp?.ProductId,
            //        ProductIdSd = x.ProductId,
            //        ProductIdKg = tmp?.ProductIdKg,
            //        ProductIdBf = tmp?.ProductIdBf,
            //        ProductIdNb = tmp?.ProductIdBf,
            //        QtySd = x.Qty,
            //        Qty = x.Qty
            //    });
            //});

            r3.ForEach(x => {
                var tmp = res.Where(i => i.ProductIdBf == x.ProductId).FirstOrDefault();
                //if (tmp == null) throw new AppException($"{x.ProductId}找不到对应的统称");
                r.Add(new Auxiliary_Look
                {
                    ProductId = tmp?.ProductId,
                    ProductIdBf = x.ProductId,
                    ProductIdSd = tmp?.ProductIdSd,
                    ProductIdKg = tmp?.ProductIdKg,
                    ProductIdNb = tmp?.ProductIdBf,
                    QtyBf = x.Qty,
                    Qty = x.Qty
                });
            });
            //r4.ForEach(x =>
            //{
            //    var tmp = res.Where(i => i.ProductIdBf == x.ProductId).FirstOrDefault();
            //    //if (tmp == null) throw new AppException($"{x.ProductId}找不到对应的统称");
            //    r.Add(new Chemistry_Look
            //    {
            //        ProductId = tmp?.ProductId,
            //        ProductIdNb = x.ProductId,
            //        ProductIdSd = tmp?.ProductIdSd,
            //        ProductIdKg = tmp?.ProductIdKg,
            //        ProductIdBf = tmp?.ProductIdBf,
            //        QtyNb = x.Qty,
            //        Qty = x.Qty
            //    });
            //});
            //将数据进行整合，重复的数量进行累加，合并成一条
            //var data = r.GroupBy(x => x.ProductId).Select(x => new Chemistry_Look
            //{
            //    ProductId = x.Key,
            //    Qty = x.Sum(x => x.Qty),
            //    ProductIdKg = x.Min(x => x.ProductIdKg),
            //    ProductIdSd = x.Min(x => x.ProductIdSd),
            //    ProductIdBf = x.Min(x => x.ProductIdBf),
            //    ProductIdNb = x.Min(x => x.ProductIdNb),
            //    QtyKg = x.Sum(x => x.QtyKg),
            //    QtySd = x.Sum(x => x.QtySd),
            //    QtyBf = x.Sum(x => x.QtyBf),
            //    QtyNb = x.Sum(x => x.QtyNb),

            //}).ToList();

            await Db.DoDeleteAsync<Auxiliary_Look>(x => x.IsValid >= 0, true);
            //await Db.DoInsertAsync<Chemistry_Look>(data);
            await Db.DoInsertAsync<Auxiliary_Look>(r);
        }

        public async Task<List<ResultAdd>> SyncBlankInventory_KongGang()
        {
            var qDomain = new List<object> {
                //网页开发者模式中Payload中的domain
                new List<object> { "location_id", "child_of", 80 },
                new List<object> {"location_id.scrap_location", "=", false}
            };

            var qFields = new List<string> {
                "product_id",
                "lot_id",
                "qty",
                "grade",
                "spec"
            };
            var qPage = new
            {
                context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
                limit = 10000,
                offset = 0,
                order = "product_id desc",
            };

            var resp = await CallSearchRead("stock.quant", qDomain, qFields, qPage);

            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];

            if (res == null || res.Count <= 0)
            {
                return null;
            }
            var r = new List<ResultAdd>();

            for (var i = 0; i < res.Count; i++)
            {
                var x = (JObject)res[i];

                    r.Add(new ResultAdd
                    {
                        //ProductId = x["product_id"] is JArray ? JArray.FromObject(x["product_id"])[1].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                        ProductId = x["product_id"] is JArray ? JArray.FromObject(x["product_id"])[1].ToString(): "",
                        Qty = (decimal)x["qty"],

                    });

            }
            return r;
        }

        public async Task<List<ResultAdd>> SyncBlankInventoryBH_KongGang()
        {
            var qDomain = new List<object> {
                //网页开发者模式中Payload中的domain
                new List<object> { "location_id", "child_of", 80 },
                new List<object> {"location_id.scrap_location", "=", false}
            };

            var qFields = new List<string> {
                "product_id",
                "lot_id",
                "qty",
                "grade",
                "spec",
                "inventory_age"
            };
            var qPage = new
            {
                context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
                limit = 10000,
                offset = 0,
                order = "product_id desc",
            };

            var resp = await CallSearchRead("stock.quant", qDomain, qFields, qPage);

            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];

            if (res == null || res.Count <= 0)
            {
                return null;
            }
            var r = new List<ResultAdd>();
            Console.WriteLine("空港毛坯库存批次总数：");
            Console.WriteLine(res.Count);

            for (var i = 0; i < res.Count; i++)
            {
                var x = (JObject)res[i];

                // 通过毛坯库获取的字段：产品、批次、数量、性能、规格
                // 提取 lot_id 数组的第二个元素（索引 1）
                string temp = x["lot_id"][1].ToString();
                Console.WriteLine(temp);
                //string lot = Regex.Replace(temp, @"\（.*?\）", "");  //去除括号里的内容，只保留批号 (（
                string lot = temp.Length >= 7 ? temp.Substring(0, 7) : temp;
                Console.WriteLine(lot);
                //string lot = Regex.Replace(temp, @"\(.*?\)", "");  //去除括号里的内容，只保留批号
                var qDomain2 = new List<object>
                {
                    //网页开发者模式中Payload中的domain，需要在网页右上角设定筛选条件才有，没有的话可以根据实际情况写
                    new List<object> { "blank_name", "=", lot}
                };
                // 通过BH检测获取的字段：常温br hcj值
                //需要在添加个  工厂  字段
                var qFields2 = new List<string>
                {
                    "br_normal",
                    "hcj_normal",
                };
                var qPage2 = new
                {
                    context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
                    limit = 10000,
                    offset = 0
                };
                var resp2 = await CallSearchReadBH("atm.qc.inspect.bh", qDomain2, qFields2, qPage2);
                var res2 = (JArray)resp2["result"];
                if (res2 == null || res2.Count <= 0)
                {
                    Console.WriteLine("未找到对应批次BH值");
                    continue;
                }
                var y = (JObject)res2[0];
                r.Add(new ResultAdd
                {
                    ProductId = x["product_id"] is JArray ? JArray.FromObject(x["product_id"])[1].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                    Lot = temp,
                    Qty = (decimal)x["qty"],
                    Grade = x["grade"] is JArray ? JArray.FromObject(x["grade"])[1].ToString() : "",
                    Spec = x["spec"].ToString(),
                    InventoryAge = (int)x["inventory_age"],
                    Br = (decimal)y["br_normal"],
                    Hcj = (decimal)y["hcj_normal"],
                    Location = "空港",

                }); ; ;
                Console.WriteLine(i);

            }
            Console.WriteLine("空港毛坯库存中有BH值的批次总数：");
            Console.WriteLine(r.Count);
            return r;
        }


        public async Task<List<ResultAdd>> SyncBlankInventory_AiKe()
        {
            var qDomain = new List<object> {
                //网页开发者模式中Payload中的domain
                new List<object> { "location_id", "child_of", 80 },
                new List<object> {"location_id.scrap_location", "=", false}
            };

            var qFields = new List<string> {
                "nc_code",
                "product_id",
                "product_uom_id",
                "qty"
            };
            var qPage = new
            {
                context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
                limit = 10000,
                offset = 0,
                // name：表示要按照名为 "name" 的字段进行排序  desc：表示降序排列（从大到小或从Z到A）如果是 asc 则表示升序排列（从小到大或从A到Z）
                order = "name desc",
            };

            var resp = await CallSearchRead_AiKe("stock.quant", qDomain, qFields, qPage);

            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];

            if (res == null || res.Count <= 0)
            {
                return null;
            }
            var r = new List<ResultAdd>();

            for (var i = 0; i < res.Count; i++)
            {
                var x = (JObject)res[i];
                r.Add(new ResultAdd
                {
                    //nc_code = x["nc_code"].ToString(),
                    ProductId = x["product_id"] is JArray ? JArray.FromObject(x["product_id"])[1].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                    //product_uom_id = x["product_uom_id"] is JArray ? JArray.FromObject(x["product_uom_id"])[1].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                    Qty = (decimal)x["qty"],

                });

            }
            return r;
        }

        public async Task<List<ResultAdd>> SyncBlankInventoryBH_AiKe()
        {
            var qDomain = new List<object> {
                //网页开发者模式中Payload中的domain
                new List<object> { "location_id", "child_of", 80 },
                new List<object> {"location_id.scrap_location", "=", false}
            };

            var qFields = new List<string> {
                "product_id",
                "lot_id",
                "qty",
                "grade",
                "spec",
                "inventory_age"
            };
            var qPage = new
            {
                context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
                limit = 10000,
                offset = 0,
                // name：表示要按照名为 "name" 的字段进行排序  desc：表示降序排列（从大到小或从Z到A）如果是 asc 则表示升序排列（从小到大或从A到Z）
                //order = "name desc",
            };

            var resp = await CallSearchRead_AiKe("stock.quant", qDomain, qFields, qPage);

            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];

            if (res == null || res.Count <= 0)
            {
                return null;
            }
            var r = new List<ResultAdd>();
            Console.WriteLine("爱科毛坯库存批次总数：");
            Console.WriteLine(res.Count);

            for (var i = 0; i < res.Count; i++)
            {
                var x = (JObject)res[i];

                // 通过毛坯库获取的字段：产品、批次、数量、性能、规格
                // 提取 lot_id 数组的第二个元素（索引 1）
                string temp = x["lot_id"][1].ToString();
                Console.WriteLine(temp);
                //string lot = Regex.Replace(temp, @"\（.*?\）", "");  //去除括号里的内容，只保留批号 (（
                string lot = temp;
                Console.WriteLine(lot);
                //string lot = Regex.Replace(temp, @"\(.*?\)", "");  //去除括号里的内容，只保留批号
                var qDomain2 = new List<object>
                {
                    //网页开发者模式中Payload中的domain，需要在网页右上角设定筛选条件才有，没有的话可以根据实际情况写
                    new List<object> { "blank_name", "=", lot}
                };
                // 通过BH检测获取的字段：常温br hcj值
                //需要在添加个  工厂  字段
                var qFields2 = new List<string>
                {
                    "br_normal",
                    "hcj_normal",
                };
                var qPage2 = new
                {
                    context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
                    limit = 10000,
                    offset = 0
                };

                var resp2 = await CallSearchReadBH_AiKe("atm.qc.inspect.bh", qDomain2, qFields2, qPage2);
                var res2 = (JArray)resp2["result"];
                if (res2 == null || res2.Count <= 0)
                {
                    continue;
                }
                var y = (JObject)res2[0];
                r.Add(new ResultAdd
                {
                    ProductId = x["product_id"] is JArray ? JArray.FromObject(x["product_id"])[1].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                    Lot = temp,
                    Qty = (decimal)x["qty"],
                    Grade = x["grade"] is JArray ? JArray.FromObject(x["grade"])[1].ToString() : "",
                    Spec = x["spec"].ToString(),
                    InventoryAge = (int)x["inventory_age"],
                    Br = (decimal)y["br_normal"],
                    Hcj = (decimal)y["hcj_normal"],
                    Location = "爱科",

                }); ; ;
                Console.WriteLine(i);


            }
            Console.WriteLine("爱科毛坯库存中有BH值的批次总数：");
            Console.WriteLine(r.Count);
            return r;
        }

        public async Task<List<ResultAdd>> SyncBlankInventory_BeiFang(string location)
        {
            var qDomain = new List<object>(); // 先声明变量，但不初始化

            if (location == "beifang")
            {
                qDomain = new List<object>
                {
                    new List<object> { "location_id", "child_of", 80 },
                    new List<object> {"location_id.scrap_location", "=", false}
            };
            }
            else if (location == "ningbo")
            {
                qDomain = new List<object>
                {
                    new List<object> { "location_id", "child_of", 27222 },
                    new List<object> {"location_id.scrap_location", "=", false}
                };
            }

            var qFields = new List<string> {
                "product_id",
                "lot_id",
                "qty",
                "grade",
                "spec"
            };
            var qPage = new
            {
                context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
                limit = 10000,
                offset = 0,
                order = "product_id desc",
            };

            var resp = await CallSearchRead_BeiFang("stock.quant", qDomain, qFields, qPage);

            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];

            if (res == null || res.Count <= 0)
            {
                return null;
            }
            var r = new List<ResultAdd>();

            for (var i = 0; i < res.Count; i++)
            {
                var x = (JObject)res[i];
               


            }
            return r;
        }

        public async Task<List<ResultAdd>> SyncBlankInventoryBH_BeiFang(string location)
        {
            var qDomain = new List<object>(); // 先声明变量，但不初始化
            string location_real = "";
            if (location == "beifang")
            {
                location_real = "北方";
                qDomain = new List<object>
                {
                    new List<object> { "location_id", "child_of", 80 },
                    new List<object> {"location_id.scrap_location", "=", false}
            };
            }
            else if (location == "ningbo")
            {
                location_real = "宁波";
                qDomain = new List<object>
                {
                    new List<object> { "location_id", "child_of", 27222 },
                    new List<object> {"location_id.scrap_location", "=", false}
                };
            }

            var qFields = new List<string> {
                "product_id",
                "lot_id",
                "quantity",
                "grade",
                "spec",
                "inventory_age"
            };
            var qPage = new
            {
                context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
                limit = 10000,
                offset = 0,
                order = "product_id desc",
            };

            var resp = await CallSearchRead_BeiFang("stock.quant", qDomain, qFields, qPage);

            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];

            if (res == null || res.Count <= 0)
            {
                return null;
            }
            var r = new List<ResultAdd>();
            Console.WriteLine("北方/宁波毛坯库存批次总数：");
            Console.WriteLine(res.Count);

            for (var i = 0; i < res.Count; i++)
            {
                var x = (JObject)res[i];

                // 通过毛坯库获取的字段：产品、批次、数量、性能、规格
                // 提取 lot_id 数组的第二个元素（索引 1）
                string temp = x["lot_id"][1].ToString();
                Console.WriteLine(temp);
                //string lot = Regex.Replace(temp, @"\（.*?\）", "");  //去除括号里的内容，只保留批号 (（
                string lot = temp;
                Console.WriteLine(lot);
                //string lot = Regex.Replace(temp, @"\(.*?\)", "");  //去除括号里的内容，只保留批号
                var qDomain2 = new List<object>
                {
                    //网页开发者模式中Payload中的domain，需要在网页右上角设定筛选条件才有，没有的话可以根据实际情况写
                    new List<object> { "blank_name", "=", lot}
                };
                // 通过BH检测获取的字段：常温br hcj值
                //需要在添加个  工厂  字段
                var qFields2 = new List<string>
                {
                    "br_normal",
                    "hcj_normal",
                };
                var qPage2 = new
                {
                    context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
                    limit = 10000,
                    offset = 0
                };

                var resp2 = await CallSearchReadBH_BeiFang("atm.qc.inspect.bh", qDomain2, qFields2, qPage2);
                var res2 = (JArray)resp2["result"];
                if (res2 == null || res2.Count <= 0)
                {
                    continue;
                }
                var y = (JObject)res2[0];
                r.Add(new ResultAdd
                {
                    ProductId = x["product_id"] is JArray ? JArray.FromObject(x["product_id"])[1].ToString(): "",
                    Lot = temp,
                    Qty = (decimal)x["quantity"],
                    Grade = x["grade"] is JArray ? JArray.FromObject(x["grade"])[1].ToString() : "",
                    Spec = x["spec"].ToString(),
                    InventoryAge = (int)x["inventory_age"],
                    Br = (decimal)y["br_normal"],
                    Hcj = (decimal)y["hcj_normal"],
                    Location = location_real,

                }); ; ;
                Console.WriteLine(i);

            }
            Console.WriteLine("北方/宁波毛坯库存中有BH值的批次总数：");
            Console.WriteLine(r.Count);
            return r;
        }

        public async Task SyncBlankInventory_Deal(List<ResultAdd> r1, List<ResultAdd> r2, List<ResultAdd> r3, List<ResultAdd> r4)
        {
            if (r1 is null || r2 is null || r3 is null || r4 is null)
            {
                throw new ArgumentNullException(nameof(r1));
                throw new ArgumentNullException(nameof(r2));
                throw new ArgumentNullException(nameof(r3));
                throw new ArgumentNullException(nameof(r4));

            }
            // 从Material_Zhenghe数据表中获取所有数据
            var res = await Db.Set<Blank_Zhenghe>().ToListAsync();
            var r = new List<Blank_Look>();
            r1.ForEach(x => {
                // 将r1中的产品代码与从Material_Zhenghe数据表中获取到的产品代码对比，返回符合的Material_Zhenghe中的数据
                var tmp = res.Where(i => i.ProductIdKg == x.ProductId).FirstOrDefault();
                //if (tmp == null) throw new AppException($"{x.ProductId}找不到对应的统称");
                r.Add(new Blank_Look
                {
                    //tmp是从数据库中获取的数据
                    ProductId = tmp?.ProductId,
                    ProductIdKg = x.ProductId,
                    ProductIdSd = tmp?.ProductIdSd,
                    ProductIdBf = tmp?.ProductIdBf,
                    ProductIdNb = tmp?.ProductIdBf,
                    QtyKg = x.Qty,
                    Qty = x.Qty
                });
            });

            r2.ForEach(x =>
            {
                var tmp = res.Where(i => i.ProductIdSd == x.ProductId).FirstOrDefault();
                //if (tmp == null) throw new AppException($"{x.ProductId}找不到对应的统称");
                r.Add(new Blank_Look
                {
                    ProductId = tmp?.ProductId,
                    ProductIdSd = x.ProductId,
                    ProductIdKg = tmp?.ProductIdKg,
                    ProductIdBf = tmp?.ProductIdBf,
                    ProductIdNb = tmp?.ProductIdBf,
                    QtySd = x.Qty,
                    Qty = x.Qty
                });
            });

            r3.ForEach(x => {
                var tmp = res.Where(i => i.ProductIdBf == x.ProductId).FirstOrDefault();
                //if (tmp == null) throw new AppException($"{x.ProductId}找不到对应的统称");
                r.Add(new Blank_Look
                {
                    ProductId = tmp?.ProductId,
                    ProductIdBf = x.ProductId,
                    ProductIdSd = tmp?.ProductIdSd,
                    ProductIdKg = tmp?.ProductIdKg,
                    ProductIdNb = tmp?.ProductIdBf,
                    QtyBf = x.Qty,
                    Qty = x.Qty
                });
            });
            r4.ForEach(x =>
            {
                var tmp = res.Where(i => i.ProductIdBf == x.ProductId).FirstOrDefault();
                //if (tmp == null) throw new AppException($"{x.ProductId}找不到对应的统称");
                r.Add(new Blank_Look
                {
                    ProductId = tmp?.ProductId,
                    ProductIdNb = x.ProductId,
                    ProductIdSd = tmp?.ProductIdSd,
                    ProductIdKg = tmp?.ProductIdKg,
                    ProductIdBf = tmp?.ProductIdBf,
                    QtyNb = x.Qty,
                    Qty = x.Qty
                });
            });
            //将数据进行整合，重复的数量进行累加，合并成一条
            //var data = r.GroupBy(x => x.ProductId).Select(x => new Chemistry_Look
            //{
            //    ProductId = x.Key,
            //    Qty = x.Sum(x => x.Qty),
            //    ProductIdKg = x.Min(x => x.ProductIdKg),
            //    ProductIdSd = x.Min(x => x.ProductIdSd),
            //    ProductIdBf = x.Min(x => x.ProductIdBf),
            //    ProductIdNb = x.Min(x => x.ProductIdNb),
            //    QtyKg = x.Sum(x => x.QtyKg),
            //    QtySd = x.Sum(x => x.QtySd),
            //    QtyBf = x.Sum(x => x.QtyBf),
            //    QtyNb = x.Sum(x => x.QtyNb),

            //}).ToList();

            await Db.DoDeleteAsync<Blank_Look>(x => x.IsValid >= 0, true);
            //await Db.DoInsertAsync<Chemistry_Look>(data);
            await Db.DoInsertAsync<Blank_Look>(r);
        }

        public async Task SyncBlankInventoryBH_Deal(List<ResultAdd> r1, List<ResultAdd> r2, List<ResultAdd> r3, List<ResultAdd> r4)
        {
            if (r1 is null || r2 is null || r3 is null || r4 is null)
            {
                throw new ArgumentNullException(nameof(r1));
                throw new ArgumentNullException(nameof(r2));
                throw new ArgumentNullException(nameof(r3));
                throw new ArgumentNullException(nameof(r4));

            }
            // 从Material_Zhenghe数据表中获取所有数据
            var r = new List<Blankbh_Look>();
            r1.ForEach(x =>
            {
                r.Add(new Blankbh_Look
                {
                    //tmp是从数据库中获取的数据
                    ProductId = x?.ProductId,
                    Lot = x?.Lot,
                    Qty = (int?)(x?.Qty),
                    Grade = x?.Grade,
                    Spec = x?.Spec,
                    Br = x?.Br,
                    Hcj = x?.Hcj,
                    Location = x?.Location,
                    InventoryAge = x?.InventoryAge,

                });
            });

            r2.ForEach(x => {
                r.Add(new Blankbh_Look
                {
                    //tmp是从数据库中获取的数据
                    ProductId = x?.ProductId,
                    Lot = x?.Lot,
                    Qty = (int?)(x?.Qty),
                    Grade = x?.Grade,
                    Spec = x?.Spec,
                    Br = x?.Br,
                    Hcj = x?.Hcj,
                    Location = x?.Location,
                    InventoryAge = x?.InventoryAge,

                });
            });

            r3.ForEach(x =>
            {
                r.Add(new Blankbh_Look
                {
                    //tmp是从数据库中获取的数据
                    ProductId = x?.ProductId,
                    Lot = x?.Lot,
                    Qty = (int?)(x?.Qty),
                    Grade = x?.Grade,
                    Spec = x?.Spec,
                    Br = x?.Br,
                    Hcj = x?.Hcj,
                    Location = x?.Location,
                    InventoryAge = x?.InventoryAge,

                });
            });

            r4.ForEach(x =>
            {
                r.Add(new Blankbh_Look
                {
                    //tmp是从数据库中获取的数据
                    ProductId = x?.ProductId,
                    Lot = x?.Lot,
                    Qty = (int?)(x?.Qty),
                    Grade = x?.Grade,
                    Spec = x?.Spec,
                    Br = x?.Br,
                    Hcj = x?.Hcj,
                    Location = x?.Location,
                    InventoryAge = x?.InventoryAge,

                });
            });


            await Db.DoDeleteAsync<Blankbh_Look>(x => x.IsValid >= 0, true);
            //await Db.DoInsertAsync<Chemistry_Look>(data);
            await Db.DoInsertAsync<Blankbh_Look>(r);
        }

        public async Task<List<ResultAdd>> SyncBlackInventory_KongGang()
        {
            var qDomain = new List<object> {
                //网页开发者模式中Payload中的domain
                new List<object> { "location_id", "child_of", 92 }
            };

            var qFields = new List<string> {
                "nc_code",
                "product_id",
                "product_uom_id",
                "qty"
            };
            var qPage = new
            {
                context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
                limit = 10000,
                offset = 0,
                order = "product_id desc",
            };

            var resp = await CallSearchRead("stock.quant", qDomain, qFields, qPage);

            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];

            if (res == null || res.Count <= 0)
            {
                return null;
            }
            var r = new List<ResultAdd>();

            for (var i = 0; i < res.Count; i++)
            {
                var x = (JObject)res[i];
                r.Add(new ResultAdd
                {
                    //nc_code = x["nc_code"].ToString(),
                    ProductId = x["product_id"] is JArray ? JArray.FromObject(x["product_id"])[1].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                    //product_uom_id = x["product_uom_id"] is JArray ? JArray.FromObject(x["product_uom_id"])[1].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                    Qty = (decimal)x["qty"],

                });

            }
            return r;
        }

        public async Task<List<ResultAdd>> SyncBlackInventory_AiKe()
        {
            var qDomain = new List<object> {
                //网页开发者模式中Payload中的domain
                new List<object> { "location_id", "child_of", 92 }
            };

            var qFields = new List<string> {
                "nc_code",
                "product_id",
                "product_uom_id",
                "qty"
            };
            var qPage = new
            {
                context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
                limit = 10000,
                offset = 0,
                order = "name desc",
            };

            var resp = await CallSearchRead_AiKe("stock.quant", qDomain, qFields, qPage);

            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];

            if (res == null || res.Count <= 0)
            {
                return null;
            }
            var r = new List<ResultAdd>();

            for (var i = 0; i < res.Count; i++)
            {
                var x = (JObject)res[i];
                r.Add(new ResultAdd
                {
                    //nc_code = x["nc_code"].ToString(),
                    ProductId = x["product_id"] is JArray ? JArray.FromObject(x["product_id"])[1].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                    //product_uom_id = x["product_uom_id"] is JArray ? JArray.FromObject(x["product_uom_id"])[1].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                    Qty = (decimal)x["qty"],

                });

            }
            return r;
        }

        public async Task<List<ResultAdd>> SyncBlackInventory_BeiFang(string location)
        {
            var qDomain = new List<object>(); // 先声明变量，但不初始化

            if (location == "beifang")
            {
                qDomain = new List<object>
                {
                    new List<object> { "location_id", "child_of", 92 },
                    new List<object> {"location_id.scrap_location", "=", false}
            };
            }
            else if (location == "ningbo")
            {
                qDomain = new List<object>
                {
                    new List<object> { "location_id", "child_of", 27222 },
                    new List<object> {"location_id.scrap_location", "=", false}
                };
            }

            var qFields = new List<string> {
                "nc_code",
                "product_id",
                "product_uom_id",
                "quantity"
            };
            var qPage = new
            {
                context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
                limit = 10000,
                offset = 0,
                order = "product_id desc",
            };

            var resp = await CallSearchRead_BeiFang("stock.quant", qDomain, qFields, qPage);

            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];

            if (res == null || res.Count <= 0)
            {
                return null;
            }
            var r = new List<ResultAdd>();

            for (var i = 0; i < res.Count; i++)
            {
                var x = (JObject)res[i];
                r.Add(new ResultAdd
                {
                    //nc_code = x["nc_code"]?.ToString(),
                    //productId = x["product_id"] is JArray ? JArray.FromObject(x["product_id"])[display_name].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                    ProductId = x["product_id"]?[1]?.ToString(),
                    //product_uom_id = x["product_uom_id"]?[1]?.ToString(),
                    //product_uom_id = x["product_uom_id"] is JArray ? JArray.FromObject(x["product_uom_id"])[0].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                    Qty = (decimal)x["quantity"],

                });

            }
            return r;
        }

        public async Task SyncBlackInventory_Deal(List<ResultAdd> r1, List<ResultAdd> r2, List<ResultAdd> r3)
        {
            if (r1 is null || r2 is null || r3 is null)
            {
                throw new ArgumentNullException(nameof(r1));
                throw new ArgumentNullException(nameof(r2));
                throw new ArgumentNullException(nameof(r3));

            }
            // 从Material_Zhenghe数据表中获取所有数据
            var res = await Db.Set<Black_Zhenghe>().ToListAsync();
            var r = new List<Black_Look>();
            r1.ForEach(x => {
                // 将r1中的产品代码与从Material_Zhenghe数据表中获取到的产品代码对比，返回符合的Material_Zhenghe中的数据
                var tmp = res.Where(i => i.ProductIdKg == x.ProductId).FirstOrDefault();
                //if (tmp == null) throw new AppException($"{x.ProductId}找不到对应的统称");
                r.Add(new Black_Look
                {
                    //tmp是从数据库中获取的数据
                    ProductId = tmp?.ProductId,
                    ProductIdKg = x.ProductId,
                    ProductIdSd = tmp?.ProductIdSd,
                    ProductIdBf = tmp?.ProductIdBf,
                    ProductIdNb = tmp?.ProductIdBf,
                    QtyKg = x.Qty,
                    Qty = x.Qty
                });
            });

            r2.ForEach(x =>
            {
                var tmp = res.Where(i => i.ProductIdSd == x.ProductId).FirstOrDefault();
                //if (tmp == null) throw new AppException($"{x.ProductId}找不到对应的统称");
                r.Add(new Black_Look
                {
                    ProductId = tmp?.ProductId,
                    ProductIdSd = x.ProductId,
                    ProductIdKg = tmp?.ProductIdKg,
                    ProductIdBf = tmp?.ProductIdBf,
                    ProductIdNb = tmp?.ProductIdBf,
                    QtySd = x.Qty,
                    Qty = x.Qty
                });
            });

            r3.ForEach(x =>
            {
                var tmp = res.Where(i => i.ProductIdBf == x.ProductId).FirstOrDefault();
                //if (tmp == null) throw new AppException($"{x.ProductId}找不到对应的统称");
                r.Add(new Black_Look
                {
                    ProductId = tmp?.ProductId,
                    ProductIdBf = x.ProductId,
                    ProductIdSd = tmp?.ProductIdSd,
                    ProductIdKg = tmp?.ProductIdKg,
                    ProductIdNb = tmp?.ProductIdBf,
                    QtyBf = x.Qty,
                    Qty = x.Qty
                });
            });
            //r4.ForEach(x =>
            //{
            //    var tmp = res.Where(i => i.ProductIdBf == x.ProductId).FirstOrDefault();
            //    //if (tmp == null) throw new AppException($"{x.ProductId}找不到对应的统称");
            //    r.Add(new Black_Look
            //    {
            //        ProductId = tmp?.ProductId,
            //        ProductIdNb = x.ProductId,
            //        ProductIdSd = tmp?.ProductIdSd,
            //        ProductIdKg = tmp?.ProductIdKg,
            //        ProductIdBf = tmp?.ProductIdBf,
            //        QtyNb = x.Qty,
            //        Qty = x.Qty
            //    });
            //});
            //将数据进行整合，重复的数量进行累加，合并成一条
            //var data = r.GroupBy(x => x.ProductId).Select(x => new Chemistry_Look
            //{
            //    ProductId = x.Key,
            //    Qty = x.Sum(x => x.Qty),
            //    ProductIdKg = x.Min(x => x.ProductIdKg),
            //    ProductIdSd = x.Min(x => x.ProductIdSd),
            //    ProductIdBf = x.Min(x => x.ProductIdBf),
            //    ProductIdNb = x.Min(x => x.ProductIdNb),
            //    QtyKg = x.Sum(x => x.QtyKg),
            //    QtySd = x.Sum(x => x.QtySd),
            //    QtyBf = x.Sum(x => x.QtyBf),
            //    QtyNb = x.Sum(x => x.QtyNb),

            //}).ToList();

            await Db.DoDeleteAsync<Black_Look>(x => x.IsValid >= 0, true);
            //await Db.DoInsertAsync<Chemistry_Look>(data);
            await Db.DoInsertAsync<Black_Look>(r);
        }

        public async Task<List<ResultAdd>> SyncWhiteInventory_KongGang()
        {
            var qDomain = new List<object> {
                //网页开发者模式中Payload中的domain
                new List<object> { "location_id", "child_of", 98 }
            };

            var qFields = new List<string> {
                "nc_code",
                "product_id",
                "product_uom_id",
                "qty"
            };
            var qPage = new
            {
                context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
                limit = 10000,
                offset = 0,
                order = "product_id desc",
            };

            var resp = await CallSearchRead("stock.quant", qDomain, qFields, qPage);

            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];

            if (res == null || res.Count <= 0)
            {
                return null;
            }
            var r = new List<ResultAdd>();

            for (var i = 0; i < res.Count; i++)
            {
                var x = (JObject)res[i];
                r.Add(new ResultAdd
                {
                    //nc_code = x["nc_code"].ToString(),
                    ProductId = x["product_id"] is JArray ? JArray.FromObject(x["product_id"])[1].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                    //product_uom_id = x["product_uom_id"] is JArray ? JArray.FromObject(x["product_uom_id"])[1].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                    Qty = (decimal)x["qty"],

                });

            }
            return r;
        }

        public async Task<List<ResultAdd>> SyncWhiteInventory_AiKe()
        {
            var qDomain = new List<object> {
                //网页开发者模式中Payload中的domain
                new List<object> { "location_id", "child_of", 98 }
            };

            var qFields = new List<string> {
                "nc_code",
                "product_id",
                "product_uom_id",
                "qty"
            };
            var qPage = new
            {
                context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
                limit = 10000,
                offset = 0,
                order = "name desc",
            };

            var resp = await CallSearchRead_AiKe("stock.quant", qDomain, qFields, qPage);

            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];

            if (res == null || res.Count <= 0)
            {
                return null;
            }
            var r = new List<ResultAdd>();

            for (var i = 0; i < res.Count; i++)
            {
                var x = (JObject)res[i];
                r.Add(new ResultAdd
                {
                    //nc_code = x["nc_code"].ToString(),
                    ProductId = x["product_id"] is JArray ? JArray.FromObject(x["product_id"])[1].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                    //product_uom_id = x["product_uom_id"] is JArray ? JArray.FromObject(x["product_uom_id"])[1].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                    Qty = (decimal)x["qty"],

                });

            }
            return r;
        }

        public async Task<List<ResultAdd>> SyncWhiteInventory_BeiFang(string location)
        {
            var qDomain = new List<object>(); // 先声明变量，但不初始化

            if (location == "beifang")
            {
                qDomain = new List<object>
                {
                    new List<object> { "location_id", "child_of", 98 }
            };
            }
            else if (location == "ningbo")
            {
                qDomain = new List<object>
                {
                    new List<object> { "location_id", "child_of", 27222 },
                    new List<object> {"location_id.scrap_location", "=", false}
                };
            }

            var qFields = new List<string> {
                "nc_code",
                "product_id",
                "product_uom_id",
                "quantity"
            };
            var qPage = new
            {
                context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
                limit = 10000,
                offset = 0,
                order = "product_id desc",
            };

            var resp = await CallSearchRead_BeiFang("stock.quant", qDomain, qFields, qPage);

            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];

            if (res == null || res.Count <= 0)
            {
                return null;
            }
            var r = new List<ResultAdd>();

            for (var i = 0; i < res.Count; i++)
            {
                var x = (JObject)res[i];
                r.Add(new ResultAdd
                {
                    //nc_code = x["nc_code"]?.ToString(),
                    //productId = x["product_id"] is JArray ? JArray.FromObject(x["product_id"])[display_name].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                    ProductId = x["product_id"]?[1]?.ToString(),
                    //product_uom_id = x["product_uom_id"]?[1]?.ToString(),
                    //product_uom_id = x["product_uom_id"] is JArray ? JArray.FromObject(x["product_uom_id"])[0].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                    Qty = (decimal)x["quantity"],

                });

            }
            return r;
        }

        public async Task SyncWhiteInventory_Deal(List<ResultAdd> r1, List<ResultAdd> r2, List<ResultAdd> r3)
        {
            if (r1 is null || r2 is null || r3 is null)
            {
                throw new ArgumentNullException(nameof(r1));
                throw new ArgumentNullException(nameof(r2));
                throw new ArgumentNullException(nameof(r3));

            }
            // 从Material_Zhenghe数据表中获取所有数据
            var res = await Db.Set<White_Zhenghe>().ToListAsync();
            var r = new List<White_Look>();
            r1.ForEach(x => {
                // 将r1中的产品代码与从Material_Zhenghe数据表中获取到的产品代码对比，返回符合的Material_Zhenghe中的数据
                var tmp = res.Where(i => i.ProductIdKg == x.ProductId).FirstOrDefault();
                //if (tmp == null) throw new AppException($"{x.ProductId}找不到对应的统称");
                r.Add(new White_Look
                {
                    //tmp是从数据库中获取的数据
                    ProductId = tmp?.ProductId,
                    ProductIdKg = x.ProductId,
                    ProductIdSd = tmp?.ProductIdSd,
                    ProductIdBf = tmp?.ProductIdBf,
                    ProductIdNb = tmp?.ProductIdBf,
                    QtyKg = x.Qty,
                    Qty = x.Qty
                });
            });

            r2.ForEach(x =>
            {
                var tmp = res.Where(i => i.ProductIdSd == x.ProductId).FirstOrDefault();
                //if (tmp == null) throw new AppException($"{x.ProductId}找不到对应的统称");
                r.Add(new White_Look
                {
                    ProductId = tmp?.ProductId,
                    ProductIdSd = x.ProductId,
                    ProductIdKg = tmp?.ProductIdKg,
                    ProductIdBf = tmp?.ProductIdBf,
                    ProductIdNb = tmp?.ProductIdBf,
                    QtySd = x.Qty,
                    Qty = x.Qty
                });
            });

            r3.ForEach(x =>
            {
                var tmp = res.Where(i => i.ProductIdBf == x.ProductId).FirstOrDefault();
                //if (tmp == null) throw new AppException($"{x.ProductId}找不到对应的统称");
                r.Add(new White_Look
                {
                    ProductId = tmp?.ProductId,
                    ProductIdBf = x.ProductId,
                    ProductIdSd = tmp?.ProductIdSd,
                    ProductIdKg = tmp?.ProductIdKg,
                    ProductIdNb = tmp?.ProductIdBf,
                    QtyBf = x.Qty,
                    Qty = x.Qty
                });
            });
            //r4.ForEach(x =>
            //{
            //    var tmp = res.Where(i => i.ProductIdBf == x.ProductId).FirstOrDefault();
            //    //if (tmp == null) throw new AppException($"{x.ProductId}找不到对应的统称");
            //    r.Add(new Black_Look
            //    {
            //        ProductId = tmp?.ProductId,
            //        ProductIdNb = x.ProductId,
            //        ProductIdSd = tmp?.ProductIdSd,
            //        ProductIdKg = tmp?.ProductIdKg,
            //        ProductIdBf = tmp?.ProductIdBf,
            //        QtyNb = x.Qty,
            //        Qty = x.Qty
            //    });
            //});
            //将数据进行整合，重复的数量进行累加，合并成一条
            //var data = r.GroupBy(x => x.ProductId).Select(x => new Chemistry_Look
            //{
            //    ProductId = x.Key,
            //    Qty = x.Sum(x => x.Qty),
            //    ProductIdKg = x.Min(x => x.ProductIdKg),
            //    ProductIdSd = x.Min(x => x.ProductIdSd),
            //    ProductIdBf = x.Min(x => x.ProductIdBf),
            //    ProductIdNb = x.Min(x => x.ProductIdNb),
            //    QtyKg = x.Sum(x => x.QtyKg),
            //    QtySd = x.Sum(x => x.QtySd),
            //    QtyBf = x.Sum(x => x.QtyBf),
            //    QtyNb = x.Sum(x => x.QtyNb),

            //}).ToList();

            await Db.DoDeleteAsync<White_Look>(x => x.IsValid >= 0, true);
            //await Db.DoInsertAsync<Chemistry_Look>(data);
            await Db.DoInsertAsync<White_Look>(r);
        }


        public async Task<List<ResultAdd>> SyncFinalInventory_KongGang()
        {
            var qDomain = new List<object> {
                //网页开发者模式中Payload中的domain
                new List<object> { "location_id", "child_of", 105 },
                new List<object> { "location_id.scrap_location", "=", false },
                new List<object> { "product_id.top_order_type", "=", "product" }
            };

            var qFields = new List<string> {
                "nc_code",
                "product_id",
                "product_uom_id",
                "qty"
            };
            var qPage = new
            {
                context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
                limit = 10000,
                offset = 0,
                order = "product_id desc",
            };

            var resp = await CallSearchRead("stock.quant", qDomain, qFields, qPage);

            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];

            if (res == null || res.Count <= 0)
            {
                return null;
            }
            var r = new List<ResultAdd>();

            for (var i = 0; i < res.Count; i++)
            {
                var x = (JObject)res[i];
                r.Add(new ResultAdd
                {
                    //nc_code = x["nc_code"].ToString(),
                    ProductId = x["product_id"] is JArray ? JArray.FromObject(x["product_id"])[1].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                    //product_uom_id = x["product_uom_id"] is JArray ? JArray.FromObject(x["product_uom_id"])[1].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                    Qty = (decimal)x["qty"],

                });

            }
            return r;
        }

        public async Task<List<ResultAdd>> SyncFinalInventory_AiKe()
        {
            var qDomain = new List<object> {
                //网页开发者模式中Payload中的domain
                new List<object> { "location_id", "child_of", 105 },
                new List<object> { "location_id.scrap_location", "=", false },
                new List<object> { "product_id.top_order_type", "=", "product" }
            };

            var qFields = new List<string> {
                "nc_code",
                "product_id",
                "product_uom_id",
                "qty"
            };
            var qPage = new
            {
                context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
                limit = 10000,
                offset = 0,
                order = "name desc",
            };

            var resp = await CallSearchRead_AiKe("stock.quant", qDomain, qFields, qPage);

            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];

            if (res == null || res.Count <= 0)
            {
                return null;
            }
            var r = new List<ResultAdd>();

            for (var i = 0; i < res.Count; i++)
            {
                var x = (JObject)res[i];
                r.Add(new ResultAdd
                {
                    //nc_code = x["nc_code"].ToString(),
                    ProductId = x["product_id"] is JArray ? JArray.FromObject(x["product_id"])[1].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                    //product_uom_id = x["product_uom_id"] is JArray ? JArray.FromObject(x["product_uom_id"])[1].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                    Qty = (decimal)x["qty"],

                });

            }
            return r;
        }

        public async Task<List<ResultAdd>> SyncFinalInventory_BeiFang(string location)
        {
            var qDomain = new List<object>(); // 先声明变量，但不初始化

            if (location == "beifang")
            {
                qDomain = new List<object>
                {
                    new List<object> { "location_id", "child_of", 105 },
                    new List<object> { "location_id.scrap_location", "=", false}
            };
            }
            else if (location == "ningbo")
            {
                qDomain = new List<object>
                {
                    new List<object> { "location_id", "child_of", 27243 },
                    new List<object> {"location_id.scrap_location", "=", false}
                };
            }

            var qFields = new List<string> {
                "nc_code",
                "product_id",
                "product_uom_id",
                "quantity"
            };
            var qPage = new
            {
                context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
                limit = 10000,
                offset = 0,
                order = "product_id desc",
            };

            var resp = await CallSearchRead_BeiFang("stock.quant", qDomain, qFields, qPage);

            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];

            if (res == null || res.Count <= 0)
            {
                return null;
            }
            var r = new List<ResultAdd>();

            for (var i = 0; i < res.Count; i++)
            {
                var x = (JObject)res[i];
                r.Add(new ResultAdd
                {
                    //nc_code = x["nc_code"]?.ToString(),
                    //productId = x["product_id"] is JArray ? JArray.FromObject(x["product_id"])[display_name].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                    ProductId = x["product_id"]?[1]?.ToString(),
                    //product_uom_id = x["product_uom_id"]?[1]?.ToString(),
                    //product_uom_id = x["product_uom_id"] is JArray ? JArray.FromObject(x["product_uom_id"])[0].ToString().Split(new String[] { "/" }, StringSplitOptions.None)[0] : "",
                    Qty = (decimal)x["quantity"],

                });

            }
            return r;
        }

        public async Task SyncFinalInventory_Deal(List<ResultAdd> r1, List<ResultAdd> r2, List<ResultAdd> r3, List<ResultAdd> r4)
        {
            if (r1 is null || r2 is null || r3 is null || r4 is null)
            {
                throw new ArgumentNullException(nameof(r1));
                throw new ArgumentNullException(nameof(r2));
                throw new ArgumentNullException(nameof(r3));
                throw new ArgumentNullException(nameof(r4));

            }
            // 从Material_Zhenghe数据表中获取所有数据
            var res = await Db.Set<Final_Zhenghe>().ToListAsync();
            var r = new List<Final_Look>();
            r1.ForEach(x => {
                // 将r1中的产品代码与从Material_Zhenghe数据表中获取到的产品代码对比，返回符合的Material_Zhenghe中的数据
                var tmp = res.Where(i => i.ProductIdKg == x.ProductId).FirstOrDefault();
                //if (tmp == null) throw new AppException($"{x.ProductId}找不到对应的统称");
                r.Add(new Final_Look
                {
                    //tmp是从数据库中获取的数据
                    ProductId = tmp?.ProductId,
                    ProductIdKg = x.ProductId,
                    ProductIdSd = tmp?.ProductIdSd,
                    ProductIdBf = tmp?.ProductIdBf,
                    ProductIdNb = tmp?.ProductIdBf,
                    QtyKg = x.Qty,
                    Qty = x.Qty
                });
            });

            r2.ForEach(x =>
            {
                var tmp = res.Where(i => i.ProductIdSd == x.ProductId).FirstOrDefault();
                //if (tmp == null) throw new AppException($"{x.ProductId}找不到对应的统称");
                r.Add(new Final_Look
                {
                    ProductId = tmp?.ProductId,
                    ProductIdSd = x.ProductId,
                    ProductIdKg = tmp?.ProductIdKg,
                    ProductIdBf = tmp?.ProductIdBf,
                    ProductIdNb = tmp?.ProductIdBf,
                    QtySd = x.Qty,
                    Qty = x.Qty
                });
            });

            r3.ForEach(x =>
            {
                var tmp = res.Where(i => i.ProductIdBf == x.ProductId).FirstOrDefault();
                //if (tmp == null) throw new AppException($"{x.ProductId}找不到对应的统称");
                r.Add(new Final_Look
                {
                    ProductId = tmp?.ProductId,
                    ProductIdBf = x.ProductId,
                    ProductIdSd = tmp?.ProductIdSd,
                    ProductIdKg = tmp?.ProductIdKg,
                    ProductIdNb = tmp?.ProductIdBf,
                    QtyBf = x.Qty,
                    Qty = x.Qty
                });
            });
            r4.ForEach(x =>
            {
                var tmp = res.Where(i => i.ProductIdBf == x.ProductId).FirstOrDefault();
                //if (tmp == null) throw new AppException($"{x.ProductId}找不到对应的统称");
                r.Add(new Final_Look
                {
                    ProductId = tmp?.ProductId,
                    ProductIdNb = x.ProductId,
                    ProductIdSd = tmp?.ProductIdSd,
                    ProductIdKg = tmp?.ProductIdKg,
                    ProductIdBf = tmp?.ProductIdBf,
                    QtyNb = x.Qty,
                    Qty = x.Qty
                });
            });
            //将数据进行整合，重复的数量进行累加，合并成一条
            //var data = r.GroupBy(x => x.ProductId).Select(x => new Chemistry_Look
            //{
            //    ProductId = x.Key,
            //    Qty = x.Sum(x => x.Qty),
            //    ProductIdKg = x.Min(x => x.ProductIdKg),
            //    ProductIdSd = x.Min(x => x.ProductIdSd),
            //    ProductIdBf = x.Min(x => x.ProductIdBf),
            //    ProductIdNb = x.Min(x => x.ProductIdNb),
            //    QtyKg = x.Sum(x => x.QtyKg),
            //    QtySd = x.Sum(x => x.QtySd),
            //    QtyBf = x.Sum(x => x.QtyBf),
            //    QtyNb = x.Sum(x => x.QtyNb),

            //}).ToList();

            await Db.DoDeleteAsync<Final_Look>(x => x.IsValid >= 0, true);
            //await Db.DoInsertAsync<Chemistry_Look>(data);
            await Db.DoInsertAsync<Final_Look>(r);
        }

        public async Task<List<ResultAdd>> SyncPurchaseInfo_KongGang()
        {

            var qDomain = new List<object>
            {
                "|", // OR 条件
                new List<object> { "atm_po_type", "=", "po" },
                new List<object> { "atm_po_type", "=", "order" },
                "|", // OR 条件
                new List<object> { "cate1", "ilike", "生产物料" },
                new List<object> { "cate2", "ilike", "化工材料" },
                "|", // OR 条件
                new List<object> { "cate2", "ilike", "工业气体" },
                new List<object> { "cate2", "not ilike", "包装材料" },
            };


            var qFields = new List<string> {
                "id",
                "cate1",
                "cate2",
                "user_id",
                "po_date",
                "partner_id",
                "order_line"
            };
            var qPage = new
            {
                context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
                limit = 10000,
                offset = 0
            };

            var resp = await CallSearchRead("purchase.order", qDomain, qFields, qPage);

            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];

            if (res == null || res.Count <= 0)
            {
                return null;
            }
            var r = new List<ResultAdd>();

            for (var i = 0; i < res.Count; i++)
            {
                var x = (JObject)res[i];
                //var resp2 = await CallRead_purchase_AiKe("purchase.order", (int)(x["id"]));
                var order_line = (JArray)x["order_line"];

                for (int j = 0; j < order_line.Count; j++)
                {
                    int order_line_id = (int)order_line[j];
                    var resp2 = await CallRead_purchase_KongGang("purchase.order.line", order_line_id);
                    var res2 = (JArray)resp2["result"];
                    var y = (JObject)res2[0];
                    r.Add(new ResultAdd
                    {
                        Id = (int)(x["id"]),
                        Cate1 = (string)(x["cate1"] is JArray ? JArray.FromObject(x["cate1"])[1].ToString() : ""),
                        Cate2 = (string)(x["cate2"] is JArray ? JArray.FromObject(x["cate2"])[1].ToString() : ""),
                        UserId = (string)(x["user_id"] is JArray ? JArray.FromObject(x["user_id"])[1].ToString() : ""),
                        PoDate = (string)(x["po_date"].ToString()),
                        PartnerId = (string)(x["partner_id"] is JArray ? JArray.FromObject(x["partner_id"])[1].ToString() : ""),

                        Name = (string)(y["name"].ToString()),
                        Spec = y["spec"].ToString() == "False" ? "" : y["spec"].ToString(),
                        ProductQty = (decimal)(y["product_qty"]),
                        PriceUint = (decimal)(y["price_unit"]),
                        BasePrice = (decimal)(y["base_price"]),
                        PriceSubtotal = (decimal)(y["price_subtotal"]),
                        Total = (decimal)(y["total"]),
                        ProductUom = y["product_uom"][1].ToString(),
                        Location = "空港"
                    });
                }



            }
            return r;
        }
        public async Task<List<ResultAdd>> SyncPurchaseInfo_AiKe()
        {

            var qDomain = new List<object>
            {
                "|", // OR 条件
                new List<object> { "atm_po_type", "=", "po" },
                new List<object> { "atm_po_type", "=", "order" },
                "|", // OR 条件
                new List<object> { "cate1", "ilike", "生产物料" },
                new List<object> { "cate2", "ilike", "化工材料" },
                "|", // OR 条件
                new List<object> { "cate2", "ilike", "工业气体" },
                new List<object> { "cate2", "not ilike", "包装材料" },
            };


            var qFields = new List<string> {
                "id",
                "cate1",
                "cate2",
                "user_id",
                "po_date",
                "partner_id",
                "order_line"
            };
            var qPage = new
            {
                context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
                limit = 10000,
                offset = 0
            };

            var resp = await CallSearchRead_AiKe("purchase.order", qDomain, qFields, qPage);

            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];

            if (res == null || res.Count <= 0)
            {
                return null;
            }
            var r = new List<ResultAdd>();

            for (var i = 0; i < res.Count; i++)
            {
                var x = (JObject)res[i];
                //var resp2 = await CallRead_purchase_AiKe("purchase.order", (int)(x["id"]));
                var order_line = (JArray)x["order_line"];

                for (int j = 0; j < order_line.Count; j++)
                {
                    int order_line_id = (int)order_line[j];
                    var resp2 = await CallRead_purchase_AiKe("purchase.order.line", order_line_id);
                    var res2 = (JArray)resp2["result"];
                    var y = (JObject)res2[0];
                    r.Add(new ResultAdd
                    {
                        Id = (int)(x["id"]),
                        Cate1 = (string)(x["cate1"] is JArray ? JArray.FromObject(x["cate1"])[1].ToString() : ""),
                        Cate2 = (string)(x["cate2"] is JArray ? JArray.FromObject(x["cate2"])[1].ToString() : ""),
                        UserId = (string)(x["user_id"] is JArray ? JArray.FromObject(x["user_id"])[1].ToString() : ""),
                        PoDate = (string)(x["po_date"].ToString()),
                        PartnerId = (string)(x["partner_id"] is JArray ? JArray.FromObject(x["partner_id"])[1].ToString() : ""),

                        Name = (string)(y["name"].ToString()),
                        Spec = y["spec"].ToString() == "False" ? "" : y["spec"].ToString(),
                        ProductQty = (decimal)(y["product_qty"]),
                        PriceUint = (decimal)(y["price_unit"]),
                        BasePrice = (decimal)(y["base_price"]),
                        PriceSubtotal = (decimal)(y["price_subtotal"]),
                        Total = (decimal)(y["total"]),
                        ProductUom = y["product_uom"][1].ToString(),
                        Location = "爱科"
                    });
                }



            }
            return r;
        }
        public async Task<List<ResultAdd>> SyncPurchaseInfo_BeiFang()
        {

            var qDomain = new List<object>
            {
                "|", // OR 条件
                new List<object> { "atm_po_type", "=", "po" },
                new List<object> { "atm_po_type", "=", "order" },
                "|", // OR 条件
                new List<object> { "cate1", "=", 1 },
                new List<object> { "cate1", "=", 2 },

            };


            var qFields = new List<string> {
                "id",
                "cate1",
                "cate2",
                "user_id",
                "po_date",
                "partner_id"
            };
            var qPage = new
            {
                context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
                limit = 10000,
                offset = 0
            };

            var resp = await CallSearchRead_BeiFang("purchase.order", qDomain, qFields, qPage);

            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];

            if (res == null || res.Count <= 0)
            {
                return null;
            }
            var r = new List<ResultAdd>();

            for (var i = 0; i < res.Count; i++)
            {
                var x = (JObject)res[i];
                if(JArray.FromObject(x["cate2"])[1].ToString() == "包装材料(BZ)")
                {
                    continue;
                }
                var resp2 = await CallRead_purchase_BeiFang("purchase.order", (int)(x["id"]));
                var res2 = (JArray)resp2["result"][0]["order_line"];

                for (var j = 0; j < res2.Count; j++)
                {
                    var y = (JObject)res2[j];
                    r.Add(new ResultAdd
                    {
                        Id = (int)(x["id"]),
                        Cate1 = (string)(x["cate1"] is JArray ? JArray.FromObject(x["cate1"])[1].ToString() : ""),
                        Cate2 = (x["cate2"] is JArray ? JArray.FromObject(x["cate2"])[1].ToString() : ""),
                        UserId = (string)(x["user_id"] is JArray ? JArray.FromObject(x["user_id"])[1].ToString() : ""),
                        PoDate = (string)(x["po_date"].ToString()),
                        PartnerId = (string)(x["partner_id"] is JArray ? JArray.FromObject(x["partner_id"])[1].ToString() : ""),

                        Name = y["name"].ToString(),
                        Spec = y["spec"].ToString() == "False" ? "" : y["spec"].ToString(),
                        ProductQty = (decimal)(y["product_qty"]),
                        PriceUint = (decimal)(y["price_unit"]),
                        BasePrice = (decimal)(y["base_price"]),
                        PriceSubtotal = (decimal)(y["price_subtotal"]),
                        Total = (decimal)(y["total"]),
                        ProductUom = y["product_uom"]["display_name"].ToString(),
                        Location = "北方"
                    });
                }
                
                
                
            }
            return r;
        }
        public async Task SyncPurchaseInfo_Deal(List<ResultAdd> r1, List<ResultAdd> r2, List<ResultAdd> r3)
        {
            if (r1 is null || r2 is null || r3 is null)
            {
                throw new ArgumentNullException(nameof(r1));
                throw new ArgumentNullException(nameof(r2));
                throw new ArgumentNullException(nameof(r3));

            }
            var r = new List<Purchase_Info>();
            r1.ForEach(x =>
            {
                r.Add(new Purchase_Info
                {
                    Cate1 = x?.Cate1,
                    Cate2 = x?.Cate2,
                    UserId = x?.UserId,
                    PoDate = x?.PoDate,
                    PartnerId = x?.PartnerId,
                    Name = x?.Name,
                    Spec = x?.Spec,
                    ProductQty = x?.ProductQty,
                    PriceUint = x?.PriceUint,
                    BasePrice = x?.BasePrice,
                    PriceSubtotal = x?.PriceSubtotal,
                    Total = x?.Total,
                    Location = x?.Location,
                    Product_uom = x?.ProductUom
                });
            });

            r2.ForEach(x => {
                r.Add(new Purchase_Info
                {
                    Cate1 = x?.Cate1,
                    Cate2 = x?.Cate2,
                    UserId = x?.UserId,
                    PoDate = x?.PoDate,
                    PartnerId = x?.PartnerId,
                    Name = x?.Name,
                    ProductQty = x?.ProductQty,
                    Spec = x?.Spec,
                    PriceUint = x?.PriceUint,
                    BasePrice = x?.BasePrice,
                    PriceSubtotal = x?.PriceSubtotal,
                    Total = x?.Total,
                    Location = x?.Location,
                    Product_uom = x?.ProductUom
                });
            });

            r3.ForEach(x =>
            {
                r.Add(new Purchase_Info
                {
                    Cate1 = x?.Cate1,
                    Cate2 = x?.Cate2,
                    UserId = x?.UserId,
                    PoDate = x?.PoDate,
                    PartnerId = x?.PartnerId,
                    Name = x?.Name,
                    Spec =  x?.Spec,
                    ProductQty = x?.ProductQty,
                    PriceUint = x?.PriceUint,
                    BasePrice = x?.BasePrice,
                    PriceSubtotal = x?.PriceSubtotal,
                    Total = x?.Total,
                    Location = x?.Location,
                    Product_uom = x?.ProductUom
                });
            });
                       
            await Db.DoDeleteAsync<Purchase_Info>(x => x.IsValid >= 0, true);
            //await Db.DoInsertAsync<Chemistry_Look>(data);
            await Db.DoInsertAsync<Purchase_Info>(r);
        }

        public async Task<object> SyncProductionInfo(string name)
        {
            var qDomain = new List<object> {
                new List<object> { "name", "=", name }
            };

            var qFields = new List<string> {
                "id",
                "name",
                "weight_g",
            };
            var qPage = new
            {
                limit = 1,
                offset = 0,
            };

            var resp = await CallSearchRead("atm.plm.top", qDomain, qFields, qPage);
            if (resp.ContainsKey("error"))
            {
                var message = $"{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];
            if (res == null || res.Count <= 0)
            {
                return null;
            }
            return res[0];
        }
        public async Task SyncProductInfo_Deal(List<ResultAdd> r1, string type)
        {
            if (r1 is null)
            {
                throw new ArgumentNullException(nameof(r1));

            }
            if (type == "product")
            {
                var r = new List<Product_Info_List>();
                r1.ForEach(x =>
                {
                    r.Add(new Product_Info_List
                    {
                        Product = x?.Name,
                        ProductId = x?.Id,
                    });
                });

                await Db.DoDeleteAsync<Product_Info_List>(x => x.IsValid >= 0, true);
                await Db.DoInsertAsync<Product_Info_List>(r);
            }
            else if (type == "grade")
            {
                var r = new List<Product_Info_Grade>();
                r1.ForEach(x =>
                {
                    r.Add(new Product_Info_Grade
                    {
                        Grade = x?.Name,
                        GradeId = x?.Id,
                    });
                });

                await Db.DoDeleteAsync<Product_Info_Grade>(x => x.IsValid >= 0, true);
                await Db.DoInsertAsync<Product_Info_Grade>(r);
            }
            else if (type == "steelgrade")
            {
                var r = new List<Product_Info_Steelgrade>();
                r1.ForEach(x =>
                {
                    r.Add(new Product_Info_Steelgrade
                    {
                        SteelGrade = x?.Name,
                        SteelGradeId = x?.Id,
                    });
                });

                await Db.DoDeleteAsync<Product_Info_Steelgrade>(x => x.IsValid >= 0, true);
                await Db.DoInsertAsync<Product_Info_Steelgrade>(r);
            }
            else if (type == "permeation_gongyi_id")
            {
                var r = new List<Product_Info_Permeation_Gongyi_Id>();
                r1.ForEach(x =>
                {
                    r.Add(new Product_Info_Permeation_Gongyi_Id
                    {
                        PermeationGongyi = x?.Name,
                        PermeationGongyiId = x?.Id,
                    });
                });

                await Db.DoDeleteAsync<Product_Info_Permeation_Gongyi_Id>(x => x.IsValid >= 0, true);
                await Db.DoInsertAsync<Product_Info_Permeation_Gongyi_Id>(r);
            }
            else if (type == "plating")
            {
                var r = new List<Product_Info_Plating>();
                r1.ForEach(x =>
                {
                    r.Add(new Product_Info_Plating
                    {
                        Plating = x?.Name,
                        PlatingId = x?.Id,
                    });
                });

                await Db.DoDeleteAsync<Product_Info_Plating>(x => x.IsValid >= 0, true);
                await Db.DoInsertAsync<Product_Info_Plating>(r);
            }
            else if (type == "workcenter_type")
            {
                var r = new List<Product_Info_Workcenter_Type>();
                r1.ForEach(x =>
                {
                    r.Add(new Product_Info_Workcenter_Type
                    {
                        WorkcenterType = x?.Name,
                        WorkcenterTypeId = x?.Id,
                    });
                });

                await Db.DoDeleteAsync<Product_Info_Workcenter_Type>(x => x.IsValid >= 0, true);
                await Db.DoInsertAsync<Product_Info_Workcenter_Type>(r);
            }
            else if (type == "mrp_workcenter")
            {
                var r = new List<Product_Info_Mrp_Workcenter>();
                r1.ForEach(x =>
                {
                    r.Add(new Product_Info_Mrp_Workcenter
                    {
                        MrpWorkcenter = x?.Name,
                        MrpWorkcenterId = x?.Id,
                    });
                });

                await Db.DoDeleteAsync<Product_Info_Mrp_Workcenter>(x => x.IsValid >= 0, true);
                await Db.DoInsertAsync<Product_Info_Mrp_Workcenter>(r);
            }
            else if (type == "geo_type")
            {
                var r = new List<Product_Info_Geo_Type>();
                r1.ForEach(x =>
                {
                    r.Add(new Product_Info_Geo_Type
                    {
                        GeoType = x?.Name,
                        GeoTypeId = x?.Id,
                    });
                });

                await Db.DoDeleteAsync<Product_Info_Geo_Type>(x => x.IsValid >= 0, true);
                await Db.DoInsertAsync<Product_Info_Geo_Type>(r);
            }
            else if (type == "workunit_catalog")
            {
                var r = new List<Product_Info_Workunit_Catalog_Id>();
                r1.ForEach(x =>
                {
                    r.Add(new Product_Info_Workunit_Catalog_Id
                    {
                        WorkunitCatalog = x?.Name,
                        WorkunitCatalogId = x?.Id,
                    });
                });

                await Db.DoDeleteAsync<Product_Info_Workunit_Catalog_Id>(x => x.IsValid >= 0, true);
                await Db.DoInsertAsync<Product_Info_Workunit_Catalog_Id>(r);
            }
            else if (type == "square_unit_price")
            {
                var r = new List<Product_Info_Square_Unit_Price_Id>();
                r1.ForEach(x =>
                {
                    r.Add(new Product_Info_Square_Unit_Price_Id
                    {
                        SquareUnitPrice = x?.Name,
                        SquareUnitPriceId = x?.Id,
                    });
                });

                await Db.DoDeleteAsync<Product_Info_Square_Unit_Price_Id>(x => x.IsValid >= 0, true);
                await Db.DoInsertAsync<Product_Info_Square_Unit_Price_Id>(r);
            }
            else if (type == "qc_inspect_type")
            {
                var r = new List<Product_Info_Qc_Inspect_Type>();
                r1.ForEach(x =>
                {
                    r.Add(new Product_Info_Qc_Inspect_Type
                    {
                        QcInspectType = x?.Name,
                        QcInspectTypeId = x?.Id,
                    });
                });

                await Db.DoDeleteAsync<Product_Info_Qc_Inspect_Type>(x => x.IsValid >= 0, true);
                await Db.DoInsertAsync<Product_Info_Qc_Inspect_Type>(r);
            }
        }

        //public class QualityResultAdd
        //{
        //    public int Id { get; set; }
        //    public string WaveId { get; set; }
        //    public string InspectionTime { get; set; }
        //    public string ProductId { get; set; }
        //    public string Grade { get; set; }
        //    public string Plating { get; set; }
        //    public string BlankLotName { get; set; }
        //    public string Spec { get; set; }
        //    public string AtmMonth { get; set; }
        //    public string ScheduleId { get; set; }
        //    public int OutgoingFinalQty { get; set; }
        //    public int IncomingQualifiedFinalQty { get; set; }

        //}
        //public async Task<List<QualityResultAdd>> SyncQualityDailyReport_KongGang(string name)
        //{

        //    var qDomain = new List<object>
        //    {
        //        "&", // AND 条件
        //        new List<object> { "wave_id", "!=", false },
        //        new List<object> { "wave_id", "ilike", name }
        //    };


        //    var qFields = new List<string> {
        //        "id",
        //        "wave_id",//生产波次
        //        "inspection_time",//检测日期
        //        "product_id",//产品
        //        "grade",//性能
        //        "plating",//镀层
        //        "blank_lot_name",//炉号
        //        "specification",//规格
        //        "atm_month",//安泰月
        //        "schedule_id",//订单号
        //        "outgoing_final_qty",//投料数
        //        "incoming_qualified_final_qty",//合格数

        //        "defect_blank_qty",//毛坯不良
        //        "defect_grinding_qty",//磨加工不良
        //        "defect_punching_qty",//打掏孔不良
        //        "defect_linear_qty",//线切割不良
        //        "defect_cute_qty",//切方不良
        //        "defect_variable_qty",//异形磨不良
        //        "defect_fringe_qty",//平磨不良
        //        "defect_slice_qty",//切片不良
        //        "defect_chamfer_qty",//倒角不良
        //        "defect_plating_qty",//电镀不良
        //        //"defect_permeation_qty",//渗透不良
        //        "rework_defect_qty",//电镀可返不良
        //        "chip_final_qty",//电镀检出崩边
        //        "defect_black_final_qty",//电镀检出黑磕
        //        "plating_check_fall_qty",//检包落地片
        //        "magnetization_fall_qty",//充磁不良
        //        "sampling_reliability_qty",//送测样品
        //        "material_eb_qty",//毛坯磕边
        //        "material_crack_qty",//毛坯裂纹
        //        "material_dit_qty",//毛坯砂眼
        //        //"material_impurity_qty",//毛坯杂质
        //        "material_lightspot_qty",//毛坯亮点
        //        "material_silicone_oil_qty",//毛坯硅油
        //        "material_flux_bad_qty",//毛坯磁通不良
        //        "material_oxygen_qty",//毛坯氧化
        //        "material_misc_qty",//黑皮/退料
        //        "defect_grinding_eb_qty",//磨加工磕边
        //        "defect_grinding_process_qty",//磨加工工残
        //        "defect_punching_eb_qty",//打掏孔磕边
        //        "defect_punching_process_qty",//打掏孔工残
        //        "defect_fringe_eb_qty",//平磨磕边
        //        "defect_fringe_process_qty",//平磨工残
        //        "defect_linear_eb_qty",//线切割磕边
        //        "defect_linear_process_qty",//线切割工残
        //        "defect_cute_eb_qty",//切方磕边
        //        "defect_cute_process_qty",//切方工残
        //        "defect_variable_eb_qty",//异形磨磕边
        //        "defect_variable_process_qty",//异形磨工残
        //        "defect_variable_verticality_qty",//异形磨垂直度超差
        //        "defect_variable_pit_qty",//异形磨麻坑
        //        "defect_slice_eb_qty",//切片磕边
        //        "defect_slice_process_qty",//切片工残
        //        "defect_slice_mark_qty",//切片刀痕
        //        "defect_slice_verticality_qty",//切片垂直度超差
        //        "defect_slice_size_qty",//切片垂直度超差
        //        "defect_slice_pit_qty",//切片麻坑
        //        "defect_chamfer_eb_qty",//倒角磕边
        //        "defect_chamfer_process_qty",//倒角工残
        //        "defect_chamfer_pit_qty",//倒角工残
        //        "defect_chamfer_pit_qty",//倒角工残
        //        "defect_plating_concave_pit_qty",//电镀凹坑
        //        "defect_plating_colordiff_qty",//电镀镀层色差
        //        "defect_plating_size_qty",//电镀尺寸超差
        //        "defect_plating_flux_qty",//电镀结合力不良
        //        "defect_plating_edge_broken_qty",//电镀磕边
        //        "defect_plating_paint_qty",//喷涂集漆
        //        "defect_plating_net_qty",//喷涂粘网
        //        "defect_plating_foreign_qty",//喷涂异物
        //        "defect_plating_bubble_qty",//电镀气泡
        //        "defect_plating_pit_qty",//电镀麻坑
        //        "defect_plating_disability_qty",//电镀镀残
        //        "rework_test_qty",//可返实验
        //        "rework_colordiff_qty",//可返镀层色差
        //        "rework_scratch_qty",//可返镀层划痕
        //        "rework_blister_qty",//可返起泡
        //        "rework_outoftol_qty",//可返超差
        //        "rework_edge_broken_qty",//可返磕边
        //        "rework_pit_qty",//可返凹坑
        //        "rework_paint_qty",//可返集漆
        //        "rework_foreign_qty",//可返异物
        //        "rework_net_qty",//可返粘网
        //        "rework_plating_paint_qty",//可返电镀掉漆

        //    };
        //    var qPage = new
        //    {
        //        context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
        //        limit = 10000,
        //        offset = 0
        //    };

        //    var resp = await CallSearchRead("atm.qc.inspect.visual.rate.report", qDomain, qFields, qPage);

        //    if (resp.ContainsKey("error"))
        //    {
        //        var message = $"【拉取单据】{resp["error"].ToString()}";
        //        throw new AppException(message);
        //    }
        //    var res = (JArray)resp["result"];

        //    if (res == null || res.Count <= 0)
        //    {
        //        return null;
        //    }
        //    var r = new List<QualityResultAdd>();

        //    for (var i = 0; i < res.Count; i++)
        //    {
        //        var x = (JObject)res[i];

        //        r.Add(new QualityResultAdd
        //        {
        //            WaveId = x["wave_id"] is JArray ? JArray.FromObject(x["wave_id"])[1].ToString() : "",
        //            InspectionTime = x["inspection_time"].ToString(),
        //            ProductId = x["product_id"].ToString(),
        //            Grade = x["grade"].ToString(),
        //            Plating = x["plating"].ToString(),
        //            BlankLotName = x["blank_lot_name"].ToString(),
        //            Spec = x["specification"].ToString(),
        //            AtmMonth = x["atm_month"].ToString(),
        //            ScheduleId = x["schedule_id"].ToString(),
        //            OutgoingFinalQty = (int)x["outgoing_final_qty"],
        //            IncomingQualifiedFinalQty = (int)x["incoming_qualified_final_qty"]

        //        });

        //    }
        //    return r;
        //}
        //public async Task<List<QualityResultAdd>> SyncQualityDailyReport_AiKe(string name)
        //{

        //    var qDomain = new List<object>
        //    {
        //        "&", // AND 条件
        //        new List<object> { "wave_id", "!=", false },
        //        new List<object> { "wave_id", "ilike", name }
        //    };


        //    var qFields = new List<string> {
        //        "id",
        //        "wave_id",//生产波次
        //        "inspection_time",//检测日期
        //        "product_id",//产品
        //        "grade",//性能
        //        "plating",//镀层
        //        "blank_lot_name",//炉号
        //        "specification",//规格
        //        "atm_month",//安泰月
        //        "schedule_id",//订单号
        //        "outgoing_final_qty",//投料数
        //        "incoming_qualified_final_qty",//合格数

        //        "defect_blank_qty",//毛坯不良
        //        "defect_grinding_qty",//磨加工不良
        //        "defect_punching_qty",//打掏孔不良
        //        "defect_linear_qty",//线切割不良
        //        "defect_cute_qty",//切方不良
        //        "defect_variable_qty",//异形磨不良
        //        "defect_fringe_qty",//平磨不良
        //        "defect_slice_qty",//切片不良
        //        "defect_chamfer_qty",//倒角不良
        //        "defect_plating_qty",//电镀不良
        //        //"defect_permeation_qty",//渗透不良
        //        "rework_defect_qty",//电镀可返不良
        //        "chip_final_qty",//电镀检出崩边
        //        "defect_black_final_qty",//电镀检出黑磕
        //        "plating_check_fall_qty",//检包落地片
        //        "magnetization_fall_qty",//充磁不良
        //        "sampling_reliability_qty",//送测样品
        //        "material_eb_qty",//毛坯磕边
        //        "material_crack_qty",//毛坯裂纹
        //        "material_dit_qty",//毛坯砂眼
        //        //"material_impurity_qty",//毛坯杂质
        //        "material_lightspot_qty",//毛坯亮点
        //        "material_silicone_oil_qty",//毛坯硅油
        //        "material_flux_bad_qty",//毛坯磁通不良
        //        "material_oxygen_qty",//毛坯氧化
        //        "material_misc_qty",//黑皮/退料
        //        "defect_grinding_eb_qty",//磨加工磕边
        //        "defect_grinding_process_qty",//磨加工工残
        //        "defect_punching_eb_qty",//打掏孔磕边
        //        "defect_punching_process_qty",//打掏孔工残
        //        "defect_fringe_eb_qty",//平磨磕边
        //        "defect_fringe_process_qty",//平磨工残
        //        "defect_linear_eb_qty",//线切割磕边
        //        "defect_linear_process_qty",//线切割工残
        //        "defect_cute_eb_qty",//切方磕边
        //        "defect_cute_process_qty",//切方工残
        //        "defect_variable_eb_qty",//异形磨磕边
        //        "defect_variable_process_qty",//异形磨工残
        //        "defect_variable_verticality_qty",//异形磨垂直度超差
        //        "defect_variable_pit_qty",//异形磨麻坑
        //        "defect_slice_eb_qty",//切片磕边
        //        "defect_slice_process_qty",//切片工残
        //        "defect_slice_mark_qty",//切片刀痕
        //        "defect_slice_verticality_qty",//切片垂直度超差
        //        "defect_slice_size_qty",//切片垂直度超差
        //        "defect_slice_pit_qty",//切片麻坑
        //        "defect_chamfer_eb_qty",//倒角磕边
        //        "defect_chamfer_process_qty",//倒角工残
        //        "defect_chamfer_pit_qty",//倒角工残
        //        "defect_chamfer_pit_qty",//倒角工残
        //        "defect_plating_concave_pit_qty",//电镀凹坑
        //        "defect_plating_colordiff_qty",//电镀镀层色差
        //        "defect_plating_size_qty",//电镀尺寸超差
        //        "defect_plating_flux_qty",//电镀结合力不良
        //        "defect_plating_edge_broken_qty",//电镀磕边
        //        "defect_plating_paint_qty",//喷涂集漆
        //        "defect_plating_net_qty",//喷涂粘网
        //        "defect_plating_foreign_qty",//喷涂异物
        //        "defect_plating_bubble_qty",//电镀气泡
        //        "defect_plating_pit_qty",//电镀麻坑
        //        "defect_plating_disability_qty",//电镀镀残
        //        "rework_test_qty",//可返实验
        //        "rework_colordiff_qty",//可返镀层色差
        //        "rework_scratch_qty",//可返镀层划痕
        //        "rework_blister_qty",//可返起泡
        //        "rework_outoftol_qty",//可返超差
        //        "rework_edge_broken_qty",//可返磕边
        //        "rework_pit_qty",//可返凹坑
        //        "rework_paint_qty",//可返集漆
        //        "rework_foreign_qty",//可返异物
        //        "rework_net_qty",//可返粘网
        //        "rework_plating_paint_qty",//可返电镀掉漆

        //    };
        //    var qPage = new
        //    {
        //        context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
        //        limit = 10000,
        //        offset = 0
        //    };

        //    var resp = await CallSearchRead_AiKe("atm.qc.inspect.visual.rate.report", qDomain, qFields, qPage);

        //    if (resp.ContainsKey("error"))
        //    {
        //        var message = $"【拉取单据】{resp["error"].ToString()}";
        //        throw new AppException(message);
        //    }
        //    var res = (JArray)resp["result"];

        //    if (res == null || res.Count <= 0)
        //    {
        //        return null;
        //    }
        //    var r = new List<QualityResultAdd>();

        //    for (var i = 0; i < res.Count; i++)
        //    {
        //        var x = (JObject)res[i];

        //        r.Add(new QualityResultAdd
        //        {
        //            WaveId = x["wave_id"] is JArray ? JArray.FromObject(x["wave_id"])[1].ToString() : "",
        //            InspectionTime = x["inspection_time"].ToString(),
        //            ProductId = x["product_id"].ToString(),
        //            Grade = x["grade"].ToString(),
        //            Plating = x["plating"].ToString(),
        //            BlankLotName = x["blank_lot_name"].ToString(),
        //            Spec = x["specification"].ToString(),
        //            AtmMonth = x["atm_month"].ToString(),
        //            ScheduleId = x["schedule_id"].ToString(),
        //            OutgoingFinalQty = (int)x["outgoing_final_qty"],
        //            IncomingQualifiedFinalQty = (int)x["incoming_qualified_final_qty"]

        //        });

        //    }
        //    return r;
        //}
        //public async Task<List<QualityResultAdd>> SyncQualityDailyReport_BeiFang(string name)
        //{

        //    var qDomain = new List<object>
        //    {
        //        "&", // AND 条件
        //        new List<object> { "wave_id", "!=", false },
        //        new List<object> { "wave_id", "ilike", name }
        //    };


        //    var qFields = new List<string> {
        //        "id",
        //        "wave_id",//生产波次
        //        "inspection_time",//检测日期
        //        "product_id",//产品
        //        "grade",//性能
        //        "plating",//镀层
        //        "blank_lot_name",//炉号
        //        "specification",//规格
        //        "atm_month",//安泰月
        //        "schedule_id",//订单号
        //        "outgoing_final_qty",//投料数
        //        "incoming_qualified_final_qty",//合格数

        //        "defect_blank_qty",//毛坯不良
        //        "defect_grinding_qty",//磨加工不良
        //        "defect_punching_qty",//打掏孔不良
        //        "defect_linear_qty",//线切割不良
        //        "defect_cute_qty",//切方不良
        //        "defect_variable_qty",//异形磨不良
        //        "defect_fringe_qty",//平磨不良
        //        "defect_slice_qty",//切片不良
        //        "defect_chamfer_qty",//倒角不良
        //        "defect_plating_qty",//电镀不良
        //        "defect_permeation_qty",//渗透不良
        //        "rework_defect_qty",//电镀可返不良
        //        "chip_final_qty",//电镀检出崩边
        //        "defect_black_final_qty",//电镀检出黑磕
        //        "plating_check_fall_qty",//检包落地片
        //        "magnetization_fall_qty",//充磁不良
        //        "sampling_reliability_qty",//送测样品
        //        "material_eb_qty",//毛坯磕边
        //        "material_crack_qty",//毛坯裂纹
        //        "material_dit_qty",//毛坯砂眼
        //        "material_impurity_qty",//毛坯杂质
        //        "material_lightspot_qty",//毛坯亮点
        //        "material_silicone_oil_qty",//毛坯硅油
        //        "material_flux_bad_qty",//毛坯磁通不良
        //        "material_oxygen_qty",//毛坯氧化
        //        "material_misc_qty",//黑皮/退料
        //        "defect_grinding_eb_qty",//磨加工磕边
        //        "defect_grinding_process_qty",//磨加工工残
        //        "defect_punching_eb_qty",//打掏孔磕边
        //        "defect_punching_process_qty",//打掏孔工残
        //        "defect_fringe_eb_qty",//平磨磕边
        //        "defect_fringe_process_qty",//平磨工残
        //        "defect_linear_eb_qty",//线切割磕边
        //        "defect_linear_process_qty",//线切割工残
        //        "defect_cute_eb_qty",//切方磕边
        //        "defect_cute_process_qty",//切方工残
        //        "defect_variable_eb_qty",//异形磨磕边
        //        "defect_variable_process_qty",//异形磨工残
        //        "defect_variable_verticality_qty",//异形磨垂直度超差
        //        "defect_variable_pit_qty",//异形磨麻坑
        //        "defect_slice_eb_qty",//切片磕边
        //        "defect_slice_process_qty",//切片工残
        //        "defect_slice_mark_qty",//切片刀痕
        //        "defect_slice_verticality_qty",//切片垂直度超差
        //        "defect_slice_size_qty",//切片垂直度超差
        //        "defect_slice_pit_qty",//切片麻坑
        //        "defect_chamfer_eb_qty",//倒角磕边
        //        "defect_chamfer_process_qty",//倒角工残
        //        "defect_chamfer_pit_qty",//倒角工残
        //        "defect_chamfer_pit_qty",//倒角工残
        //        "defect_plating_concave_pit_qty",//电镀凹坑
        //        "defect_plating_colordiff_qty",//电镀镀层色差
        //        "defect_plating_size_qty",//电镀尺寸超差
        //        "defect_plating_flux_qty",//电镀结合力不良
        //        "defect_plating_edge_broken_qty",//电镀磕边
        //        "defect_plating_paint_qty",//喷涂集漆
        //        "defect_plating_net_qty",//喷涂粘网
        //        "defect_plating_foreign_qty",//喷涂异物
        //        "defect_plating_bubble_qty",//电镀气泡
        //        "defect_plating_pit_qty",//电镀麻坑
        //        "defect_plating_disability_qty",//电镀镀残
        //        "rework_test_qty",//可返实验
        //        "rework_colordiff_qty",//可返镀层色差
        //        "rework_scratch_qty",//可返镀层划痕
        //        "rework_blister_qty",//可返起泡
        //        "rework_outoftol_qty",//可返超差
        //        "rework_edge_broken_qty",//可返磕边
        //        "rework_pit_qty",//可返凹坑
        //        "rework_paint_qty",//可返集漆
        //        "rework_foreign_qty",//可返异物
        //        "rework_net_qty",//可返粘网
        //        "rework_plating_paint_qty",//可返电镀掉漆

        //    };
        //    var qPage = new
        //    {
        //        context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
        //        limit = 10000,
        //        offset = 0
        //    };

        //    var resp = await CallSearchRead_BeiFang("atm.qc.inspect.visual.rate.report", qDomain, qFields, qPage);

        //    if (resp.ContainsKey("error"))
        //    {
        //        var message = $"【拉取单据】{resp["error"].ToString()}";
        //        throw new AppException(message);
        //    }
        //    var res = (JArray)resp["result"];

        //    if (res == null || res.Count <= 0)
        //    {
        //        return null;
        //    }
        //    var r = new List<QualityResultAdd>();

        //    for (var i = 0; i < res.Count; i++)
        //    {
        //        var x = (JObject)res[i];

        //        r.Add(new QualityResultAdd
        //        {
        //            WaveId = x["wave_id"] is JArray ? JArray.FromObject(x["wave_id"])[1].ToString() : "",
        //            InspectionTime = x["inspection_time"].ToString(),
        //            ProductId = x["product_id"].ToString(),
        //            Grade = x["grade"].ToString(),
        //            Plating = x["plating"].ToString(),
        //            BlankLotName = x["blank_lot_name"].ToString(),
        //            Spec = x["specification"].ToString(),
        //            AtmMonth = x["atm_month"].ToString(),
        //            ScheduleId = x["schedule_id"].ToString(),
        //            OutgoingFinalQty = (int)x["outgoing_final_qty"],
        //            IncomingQualifiedFinalQty = (int)x["incoming_qualified_final_qty"]

        //        });
                
        //    }
        //    return r;
        //}


        public async Task SendEmailAsync(string toEmail, string subject, string body)
        {
            if (string.IsNullOrEmpty(subject) || string.IsNullOrEmpty(toEmail))
                throw new ArgumentException("主题和收件人邮箱不能为空");
            // 核心简化：只在需要时才改变的值
            var isType1 = subject == "CCD结单" || subject == "外观检验结单";
            var email = new MimeMessage();
            email.From.Add(new MailboxAddress(
                isType1 ? "检分厂质量预警（磁云平台）": "材料性能质量预警（磁云平台）",
                isType1 ? "jianfenchang@atmcn.com" : "quanwei@atmcn.com"
            ));
            email.To.Add(MailboxAddress.Parse(toEmail));
            email.Subject = subject;
            email.Body = new TextPart("plain") { Text = body };
            using var smtp = new SmtpClient();
            await smtp.ConnectAsync("smtp.exmail.qq.com", 465, MailKit.Security.SecureSocketOptions.SslOnConnect);
            await smtp.AuthenticateAsync(
                isType1 ? "jianfenchang@atmcn.com" : "quanwei@atmcn.com",
                isType1 ? "Jfc000969" : "Quan0325"
            );
            await smtp.SendAsync(email);
            await smtp.DisconnectAsync(true);

            //if (subject == "CCD结单" || subject == "外观检验结单")
            //{
            //    var email = new MimeMessage();

            //    email.From.Add(new MailboxAddress(
            //        "检分厂质量预警（磁云平台）",
            //        "jianfenchang@atmcn.com"
            //    ));
            //    email.To.Add(MailboxAddress.Parse(toEmail));
            //    email.Subject = subject;
            //    email.Body = new TextPart("plain") { Text = body };

            //    using var smtp = new SmtpClient();
            //    await smtp.ConnectAsync(
            //        "smtp.exmail.qq.com",
            //        465,
            //        MailKit.Security.SecureSocketOptions.SslOnConnect
            //    );
            //    await smtp.AuthenticateAsync(
            //        "jianfenchang@atmcn.com",
            //        "Jfc000969"
            //    );
            //    await smtp.SendAsync(email);
            //    await smtp.DisconnectAsync(true);
            //}
            //else
            //{
            //    var email = new MimeMessage();

            //    email.From.Add(new MailboxAddress(
            //        "材料性能质量预警（磁云平台）",
            //        "cailiao@atmcn.com"
            //    ));
            //    email.To.Add(MailboxAddress.Parse(toEmail));
            //    email.Subject = subject;
            //    email.Body = new TextPart("plain") { Text = body };

            //    using var smtp = new SmtpClient();
            //    await smtp.ConnectAsync(
            //        "smtp.exmail.qq.com",
            //        465,
            //        MailKit.Security.SecureSocketOptions.SslOnConnect
            //    );
            //    await smtp.AuthenticateAsync(
            //        "cailiao@atmcn.com",
            //        "Jfc000969"
            //    );
            //    await smtp.SendAsync(email);
            //    await smtp.DisconnectAsync(true);
            //}
           
        }
        public async Task<JObject> onchange(string model, List<object> result)
        {
            Console.WriteLine("AAAAAAAAA");
            var param = new List<object>();
            param.Add(db);
            //if (uid == null || uid == 0)
            uid = await GetOdooUid(userName, password);
            Console.WriteLine(uid);
            param.Add(uid);
            param.Add(password);
            param.Add(model);
            param.Add("onchange");
            //param.Add(new List<object> { });
            param.Add(result);
            var specification = new Dictionary<string, object>
                {
                    { "specification", new Dictionary<string, object>() }
                };
            //param.Add(specification);
            JObject data = null;
            try
            {
                data = await Call("object", "execute_kw", param);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"获取aMES数据失败，请求内容：{JsonConvert.SerializeObject(param)}，错误信息：{ex.Message}");
                throw new AppException(ex.ToString());
            }
            Console.WriteLine(data);
            Console.WriteLine("1111111111111111111111111");
            return data;
        }
        public async Task<JObject> create(string model, List<object> result)
        {
            Console.WriteLine("AAAAAAAAA");
            var param = new List<object>();
            param.Add(db);
            //if (uid == null || uid == 0)
            uid = await GetOdooUid(userName, password);
            Console.WriteLine(uid);
            param.Add(uid);
            param.Add(password);
            param.Add(model);
            param.Add("create");
            //param.Add(new List<object> { });
            param.Add(result);
            var specification = new Dictionary<string, object>
                {
                    { "specification", new Dictionary<string, object>() }
                };
            //param.Add(specification);
            JObject data = null;
            try
            {
                data = await Call("object", "execute_kw", param);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"获取aMES数据失败，请求内容：{JsonConvert.SerializeObject(param)}，错误信息：{ex.Message}");
                throw new AppException(ex.ToString());
            }
            Console.WriteLine(data);
            Console.WriteLine("1111111111111111111111111");
            return data;
        }
        public async Task<JObject> web_save(string model, List<object> result)
        {
            Console.WriteLine("AAAAAAAAA");
            var param = new List<object>();
            param.Add(db);
            //if (uid == null || uid == 0)
            uid = await GetOdooUid(userName, password);
            Console.WriteLine(uid);
            param.Add(uid);
            param.Add(password);
            param.Add(model);
            param.Add("web_save");
            //param.Add(new List<object> { });
            param.Add(result);
            var specification = new Dictionary<string, object>
                {
                    { "specification", new Dictionary<string, object>() }
                };
            param.Add(specification);
            JObject data = null;
            try
            {
                data = await Call("object", "execute_kw", param);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"获取aMES数据失败，请求内容：{JsonConvert.SerializeObject(param)}，错误信息：{ex.Message}");
                throw new AppException(ex.ToString());
            }
            Console.WriteLine(data);
            Console.WriteLine("1111111111111111111111111");
            return data;
        }

        public async Task<string> button_done(string model, List<object> result, string methord)
        {
            Console.WriteLine("AAAAAAAAA");
            var param = new List<object>();
            param.Add(db);
            //if (uid == null || uid == 0)
            uid = await GetOdooUid(userName, password);
            Console.WriteLine(uid);
            param.Add(uid);
            param.Add(password);
            param.Add(model);
            param.Add(methord);
            //param.Add(new List<object> { });
            param.Add(result);
            JObject data = null;
            try
            {
                data = await Call("object", "execute_kw", param);
                return "成功";
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                logger.LogError(ex, $"获取aMES数据失败，请求内容：{JsonConvert.SerializeObject(param)}，错误信息：{ex.Message}");
                throw new AppException(ex.ToString());
                return "失败";
            }
        }
        public async Task<string> btn_confirm(string model, List<object> result,string methord)
        {
            Console.WriteLine("AAAAAAAAA");
            var param = new List<object>();
            param.Add(db);
            //if (uid == null || uid == 0)
            uid = await GetOdooUid(userName, password);
            Console.WriteLine(uid);
            param.Add(uid);
            param.Add(password);
            param.Add(model);
            param.Add(methord);
            //param.Add(new List<object> { });
            param.Add(result);
            //var specification = new Dictionary<string, object>
            //    {
            //        { "specification", new Dictionary<string, object>() }
            //    };
            //param.Add(specification);
            JObject data = null;
            try
            {
                data = await Call("object", "execute_kw", param);
                return "成功";
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                logger.LogError(ex, $"获取aMES数据失败，请求内容：{JsonConvert.SerializeObject(param)}，错误信息：{ex.Message}");
                throw new AppException(ex.ToString());
                Console.WriteLine(data);
                Console.WriteLine("222222222");
                return "失败";
            }            
        }

        public class Purchase_Requisition
        {
            public int id { get; set; }
            public string product_name { get; set; }
            public string spec { get; set; }
            public int request_qty { get; set; }
            public string month { get; set; }
            public string year { get; set; }
            public int factory { get; set; }
            public string reason { get; set; }
            public DateTime date_required { get; set; }
            public int request_type { get; set; }
            public int mes_id { get; set; }

            public DateTime last_update_on {  get; set; }
        }
        public async Task<List<Purchase_Requisition>> SyncPurchaseRequisition_KongGang()
        {
            //userName = "koupengyuan@atmcn.com";
            //password = "kou12345";
            //url = "http://10.7.1.9/jsonrpc";
            //db = "prd0803";
            var qDomain = new List<object>
            {
                new List<object> { "cate2", "=", 26 },
                new List<object> { "request_state", "=", "approved" },
                new List<object> {"write_date",">=", DateTime.Today},
            };

            var qFields = new List<string> {
                "request_id",
                "request_type",
                "year",
                "month",
                "department_id",
                "requested_by",
                "using_department_id",
                "using_workshop_id",
                "cate2",
                "product_id",
                "spec",
                "request_qty",
                "product_qty",
                "qty_purchased",
                "product_uom_id",
                "date_required",
                "date_received",
                "qty_received",
                "supplier_id",
                "assigned_to",
                "request_state",
                "state",
                "reason",
                "write_date",
            };
            var qPage = new
            {
                context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
                limit = 10000,
                offset = 0
            };

            var resp = await CallSearchRead("purchase.request.line", qDomain, qFields, qPage);

            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            
            var res = (JArray)resp["result"];

            if (res == null || res.Count <= 0)
            {
                return null;
            }
            var r = new List<Purchase_Requisition>();
            foreach (var item in res) {
                var x = (JObject)item;
                // 处理 request_type 的转换
                var requestTypeStr = x["request_type"]?.ToString() ?? "";
                int requestType = requestTypeStr.ToLower() switch
                {
                    "plan" => 1,
                    "unplan" => 2,
                    _ => 0  // 默认值，如果都不匹配
                };
                r.Add(new Purchase_Requisition
                {
                    product_name = x["product_id"] is JArray ? JArray.FromObject(x["product_id"])[1].ToString() : "",
                    spec = x["spec"].ToString(),
                    request_qty = (int)x["request_qty"],
                    month = x["month"].ToString(),
                    year = x["year"].ToString(),
                    factory = 1, // 1表示空港
                    mes_id = (int)x["id"],
                    reason = x["reason"]?.ToString() ?? "",
                    date_required = DateTime.Parse(x["date_required"].ToString()),
                    request_type = requestType,
                    last_update_on = DateTime.Parse(x["write_date"].ToString()),
                });
            }
            return r;
        }
        public async Task<List<Purchase_Requisition>> SyncPurchaseRequisition_AiKe()
        {
            //userName = "duchao@atmcn.com";
            //password = "123456";
            //url = "http://10.7.1.9:81/jsonrpc";
            //db = "sd";
            var qDomain = new List<object>
            {
                new List<object> { "cate2", "=", 26 },
                new List<object> { "request_state", "=", "approved" },
                new List<object> {"write_date",">=", DateTime.Today},
            };


            var qFields = new List<string> {
                "request_id",
                "request_type",
                "year",
                "month",
                "department_id",
                "requested_by",
                "using_department_id",
                "using_workshop_id",
                "cate2",
                "product_id",
                "spec",
                "request_qty",
                "product_qty",
                "qty_purchased",
                "product_uom_id",
                "date_required",
                "date_received",
                "qty_received",
                "supplier_id",
                "assigned_to",
                "request_state",
                "state",
                "write_date",
            };
            var qPage = new
            {
                context = new { lang = "zh_CN", tz = "Asia/Shanghai" },
                limit = 10000,
                offset = 0
            };

            var resp = await CallSearchRead_AiKe("purchase.request.line", qDomain, qFields, qPage);

            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }

            var res = (JArray)resp["result"];

            if (res == null || res.Count <= 0)
            {
                return null;
            }
            var r = new List<Purchase_Requisition>();
            foreach (var item in res)
            {
                var x = (JObject)item;
                // 处理 request_type 的转换
                var requestTypeStr = x["request_type"]?.ToString() ?? "";
                int requestType = requestTypeStr.ToLower() switch
                {
                    "plan" => 1,
                    "unplan" => 2,
                    _ => 0  // 默认值，如果都不匹配
                };
                r.Add(new Purchase_Requisition
                {
                    product_name = x["product_id"] is JArray ? JArray.FromObject(x["product_id"])[1].ToString() : "",
                    spec = x["spec"].ToString(),
                    request_qty = (int)x["request_qty"],
                    month = x["month"].ToString(),
                    year = x["year"].ToString(),
                    factory = 2, // 2表示爱科
                    mes_id = (int)x["id"],
                    reason = x["reason"]?.ToString() ?? "",
                    date_required = DateTime.Parse(x["date_required"].ToString()),
                    request_type = requestType,
                    last_update_on = DateTime.Parse(x["write_date"].ToString()),
                });
            }
            return r;
        }
        public async Task<List<Purchase_Requisition>> SyncPurchaseRequisition_BeiFang()
        {
            userName = "duyang@atmcn.com";
            password = "Antai@2025";
            url = "http://10.16.12.80/jsonrpc";
            db = "bt";
            
            var qPage = new
            {
                limit = 10000,
                offset = 0,
            };
            var domain = new List<object>
            {
                "&", "&",
                new List<object> { "product_qty", ">", 0 },
                new List<object> { "cate2", "=", 1 },
                new List<object> { "request_state", "=", "approved" },
                new List<object> {"write_date",">=", DateTime.Today},
            };
            var product_name = new Dictionary<string, object>
            {
                {"fields",new Dictionary<string, object>
                    {
                    {
                        "display_name",new Dictionary<string,object>()
                    }
                    }

                },
            };
            var cate2 = new Dictionary<string, object>
            {
                {"fields",new Dictionary<string, object>
                    {
                    {
                        "display_name",new Dictionary<string,object>()
                    }
                    }

                },
            };
            
            var specification = new Dictionary<string, object>
            {
                {"cate2",cate2 },
                {"date_required", new Dictionary<string, object>() },
                {"date_received", new Dictionary<string, object>() },
                {"line_state", new Dictionary<string, object>() },
                {"month" ,new Dictionary<string, object>() },
                {"year", new Dictionary<string, object>() },
                {"product_qty", new Dictionary<string, object>() },
                {"qty_purchased", new Dictionary<string, object>() },
                {"qty_received", new Dictionary<string, object>() },
                {"request_qty",new Dictionary<string, object>() },
                {"request_type", new Dictionary<string, object>() },
                {"spec",new Dictionary<string,object>() },
                {"reason",new Dictionary<string,object>() },
                {"write_date",new Dictionary<string,object>() },
                {"product_id",product_name },
             };
            var result = new Dictionary<string, object>
            {
                { "domain", domain },
                { "specification", specification }
            };
            var resp = await Get_web_search_read("purchase.request.line", result);
            var r = new List<Purchase_Requisition>();
            var res = resp["result"];
            var records = res["records"] as JArray;
            if (records != null)
            {
                foreach (var item in records)
                {
                    var x = (JObject)item;
                    // 处理 request_type 的转换
                    var requestTypeStr = x["request_type"]?.ToString() ?? "";
                    int requestType = requestTypeStr.ToLower() switch
                    {
                        "plan" => 1,
                        "unplan" => 2,
                        _ => 0  // 默认值，如果都不匹配
                    };
                    r.Add(new Purchase_Requisition
                    {
                        product_name = x["product_id"]?["display_name"]?.ToString() ?? "",
                        spec = x["spec"]?.ToString() ?? "",
                        request_qty = x["request_qty"]?.ToObject<int>() ?? 0,
                        month = x["month"]?.ToString() ?? "",
                        year = x["year"]?.ToString() ?? "",
                        factory = 3, // 3表示北方
                        mes_id = (int)x["id"],
                        reason = x["reason"]?.ToString() ?? "",
                        date_required = DateTime.TryParse(x["date_required"]?.ToString(), out var date) ?
                            date : DateTime.MinValue,
                        request_type = requestType,
                        last_update_on = DateTime.Parse(x["write_date"].ToString()),
                    });
                }
            }
            //return records;
            
            return r;
        }

        public async Task SyncPurchaseRequisitionDeal(List<Purchase_Requisition> r1, List<Purchase_Requisition> r2, List<Purchase_Requisition> r3)
        {
            var lists = new[] { r1, r2, r3 }.Where(list => list != null);
            var r = new List<Purchase_Requisition>();
            foreach (var list in lists)
            {
                var validItems = list.Where(x => x != null).Select(x => new Purchase_Requisition
                {
                    product_name = x?.product_name,
                    spec = x?.spec,
                    request_qty = (int)x?.request_qty,
                    date_required = (DateTime)x?.date_required,
                    reason = x?.reason,
                    request_type = (int)x?.request_type,
                    factory = (int)x?.factory,
                    mes_id = (int)x?.mes_id,
                    month = x?.month,
                    year = x?.year,
                    last_update_on = (DateTime)x?.last_update_on,
                });

                r.AddRange(validItems);
            }
            if (r.Count > 0)
            {
                Console.WriteLine($"开始插入数据，数量：{r.Count}");
                Console.WriteLine($"r的数据内容：{System.Text.Json.JsonSerializer.Serialize(r, new JsonSerializerOptions { WriteIndented = true })}");
                var result = await Db.Storageable(r)
                .WhereColumns(x => new { x.factory, x.mes_id }) // 指定判断重复的列
                .SplitInsert(it => !it.Any()) // 不存在时插入
                .SplitIgnore(it => it.Any())  // 存在时忽略
                .ExecuteCommandAsync();
                Console.WriteLine($"受影响的行数： {result} ");
            }
            
            //await Db.DoDeleteAsync<Purchase_Requisition>(x => x.id >= 0, true);
            //await Db.DoInsertAsync<Purchase_Requisition>(r);
        }
    }
}
